简体   繁体   中英

angularjs ng-pattern regex for 4 digits and 2 decimal

I am trying to create a Regex for a number with maximum 4 digits and if the input has decimal it has to have 2 digits - .20 and not .1 . tried:

ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" //fail for 666666, .10, .1

Examples for valid inputs:

100.10
100
3000.10

Example for invalid:

10000 //has more then 4 digits before decimal
100.1 //has only 1 digit after decimal
.10 //has no digits before decimal

Thanks for any help.

Use {#,#} to limit the number of digits to 1 to 4

Try

^[0-9]{1,4}(\\.[0-9][0-9])?$

Use ( )? to make an optional two-digit decimal part

The problem with using the {1,2} is that it allows one or two digits, when you really only want two. And I assume you want to enforce a rule that if they have a ".", they must have two digits?

For example

var patt = /^[0-9]{1,4}(\.[0-9][0-9])?$/i

"1011.11".match(patt)!==null
"1011.1".match(patt)!==null

Returns

true
false

With gratitude to Sebastian Proske and Wiktor Stribiżew

For pointing out the need to escape the .

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