开发者

regex to detect leading zeros and check the lenght from 0 to 12 digits

开发者 https://www.devze.com 2022-12-18 23:48 出处:网络
Hi I have a javascript function that checks for signed integer with 0 to 12 length, i al开发者_开发技巧so want to see if there are any leading 0\'slike 0012 should return false.

Hi I have a javascript function that checks for signed integer with 0 to 12 length, i al开发者_开发技巧so want to see if there are any leading 0's like 0012 should return false.

function sInteger0to12(str) {
    str = str.replace(/^\s+|\s+$/g, '');
    return /^[-+]?\d{0,12}$/.test(str);
}

any help will be appreciated.


I'm assuming that the following should match:

1
+1
-1
0
-123456789012
<empty>

And these should fail:

-
+
01
-01
1234567890123
00
+0
-0

If you disagree with my decisions above, please let me know and I will try to fix the regex.

Here's a regex you can use:

/^([-+]?[1-9]\d{,11}|0)?$/


Like this:

 /^[-+]?[1-9]\d{0,11}$/

You'll need to check for '0' separately.


You need to cover three cases

  1. an empty string
  2. a single 0
  3. a no zero padded 1 to 12 digit number

these cases equate to

  1. ^$
  2. ^0$
  3. ^[+-]?[1-9]\d{0,11}$

which adds up to

^()|(0)|([+-]?[1-9]\d{0,11})$


This should help:

/(^0$)|(^[+-]?[1-9]\d{0,11}$)/
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号