简体   繁体   中英

validate input's float format

I need to validate an input value, 0~99.99, float type, and only two digit after the decimal point, like

valid example :

 0
 1
 .1
 .12
 12.12

invalid example :

 (empty)
 100
 123.1
 .123
 12.123

So I create this regexp

var isValid = new RegExp(/^\d{1,2}(\.\d{0,2})?$/).test(parseFloat($('#myText').val()));

any other way to check ? make code easier and simpler.

" make code easier and simpler."

OK. Here you go:

var isValid = /^\d{1,2}(\.\d{0,2})?$|^\.\d\d?$/.test($('#myText').val());

You don't need to use new RegExp() when you already have a regex literal.

Your regex didn't accept a . as the first character.

And if you pass the result of parseFloat() to .test() you are not validating what the user actually entered because parseFloat() ignores leading spaces and trailing non numeric data. So your code would accept, eg, " 12abc" as valid. If you do actually wish to ignore leading or trailing spaces you can cater for that in your regex.

You can try using the regex:

^\d{1,2}(?:\.\d{1,2})?$|^\.\d{1,2}$

regex101 demo

The regex is in two parts:

^\\d{1,2}(?:\\.\\d{1,2})?$ This will accept numbers with 2 digits, an possible decimals with up to two decimal digits.

^ matches the beginning of the line,

\\d{1,2} matches any number at least 1 time and at most 2 times.

(?: ... ) is a non capture group (this makes the regex a little more efficient by not having to keep the captured group)

? near the end indicates 0 or 1 times,

$ indicate the end of line (thus ensuring there are no more numbers).

The second part ^\\.\\d{1,2}$ accepts decimals where the first digit can be absent, as such, .1 will pass.

The first and second part are linked with an | (OR operator) which means that if a match fails for the first part, the engine will try with the second part before calling it a no-match

Here is a regular expression that also accepts leading and trailing zeros: http://regex101.com/r/hV1uD8

/^(?:0*\d{1,2})(?:\.\d{0,2}0*)?$|^(?:0*\.)(?:\d{1,2}0*)$/

Valid examples:

0 
1 
.1 
.12
12.12
23.1
023.1
12.1200
012.120
1.
1.010

Invalid:

100
123.1 
.123
12.123
12.1201

Or you could use parseFloat to take care of leading and trailing zeros and then the regular expression suggested in the other answer:

var isValid = /^\d{1,2}(?:\.\d{1,2})?$|^\.\d{1,2}$/.test(parseFloat($('#myText').val()));

but this would be less efficient because you would parse the same expression twice.

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