sergserg
sergserg

Reputation: 22264

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]

Upvotes: 15

Views: 34652

Answers (5)

Andy G
Andy G

Reputation: 19367

This one:

/0\d+/.test("0001")
// true

If "0" MUST be the first character then:

/^0\d+/.test("0001")

Upvotes: 1

pvnarula
pvnarula

Reputation: 2831

You can use something like this:-

var a = "0001";
/^[0][0-9]/.test(a)

Upvotes: 4

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

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+)?$

Upvotes: 3

Callum Rogers
Callum Rogers

Reputation: 15829

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.

Upvotes: 2

acdcjunior
acdcjunior

Reputation: 135762

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

Upvotes: 17

Related Questions