views:

84

answers:

3

Hi I have a javascript function that checks for signed integer with 0 to 12 length, i also 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.

+3  A: 

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)?$/
Mark Byers
This matches the empty string.
Anon.
I also feel that allowing the empty string is a bit off. Just pointing out that you'd changed it in the description but not edited the regex accordingly.
Anon.
Anon: now he wants to match the empty string! So I changed it back.. this is going to get confusing soon. I need to check the +0 and -0...
Mark Byers
It's always difficult to answer these questions where the OP is has extremely precise ideas about how it should work, but the actually requirements are not specified in the question... only some vague description, and then to get the exact information you have to ask repeatedly for each and every test case what the required output is.... :(
Mark Byers
This is the real reason that programming is hard - you can never get a clear spec from the start.
Anon.
Anon: Yeah - agreed. Such is life...
Mark Byers
I'm tired of waiting for the answer about the +0 and -0. The fix is to add [+-]? before the zero if +0 and -0 are both wanted as matches.
Mark Byers
no worries guys i can take it from here. Thanks for all the help!
Shah
+1  A: 

Like this:

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

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

SLaks
I took the liberty to change `112` to `11`.
Bart Kiers
+12313241, -12312312 , 1230 but not +00123 or -00123 or -021 or - or + –
Shah
I tested this worked (except for `0`, `+0`, and `-0`).
SLaks
If you really wanted to not have to check 0 separately ... `/^[-+]?([1-9]\d{0,11}|0)$/`
Anon.
A: 

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})$
Andrew Cox