简体   繁体   中英

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]

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

You can use something like this:-

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

你可以尝试这种模式,想法是使用锚点^ (用于开始)和$ (用于结束)来限制你想要的结果:

^0+\d*(?:\.\d+)?$
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.

This one:

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

If "0" MUST be the first character then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM