Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex to validate if number begins with leading zero

I need to validate some inputs using a regex.

Here are some sample use cases and expected results.

0001     - Matched
001      - Matched
01       - Matched
00.12312 - Matched
000.1232 - Matched
1        - Not matched
20       - Not matched
0.1      - Not matched
0.123123 - Not matched

What would a regex like this look like? If first char is 0 and second char is numerical[0-9] then it is invalid.

I've tried this but it doesn't work.

[0][0-9]
like image 748
sergserg Avatar asked Jun 06 '13 22:06

sergserg


4 Answers

Try this regex:

^0[0-9].*$

It will match anything starting with 0 followed by a digit.

It will "match" what you call "invalid".

The test code shall make it clearer:

var regExp = /^0[0-9].*$/
console.log(regExp.test("0001")); // true
console.log(regExp.test("001")); // true
console.log(regExp.test("01")); // true
console.log(regExp.test("00.12312")); // true
console.log(regExp.test("000.1232")); // true
console.log(regExp.test("1")); // false
console.log(regExp.test("20")); // false
console.log(regExp.test("0.1")); // false
console.log(regExp.test("0.123123")); // false
like image 154
acdcjunior Avatar answered Nov 05 '22 02:11

acdcjunior


0+[1-9][0-9]*

Matches at least one zero, followed by a nonzero digit, followed by any number of digits. Does not match the lone 0.

like image 29
Callum Rogers Avatar answered Nov 05 '22 00:11

Callum Rogers


You can use something like this:-

var a = "0001";
/^[0][0-9]/.test(a)
like image 4
pvnarula Avatar answered Nov 05 '22 00:11

pvnarula


you can try this pattern, the idea is to use anchors ^ (for begin) and $ (for end) to limit the result on what you are looking for:

^0+\d*(?:\.\d+)?$
like image 3
Casimir et Hippolyte Avatar answered Nov 05 '22 00:11

Casimir et Hippolyte