0

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.

1 Answer 1

3

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 .

Sign up to request clarification or add additional context in comments.

7 Comments

Parsing error - angular.min.js:123 Error: [$parse:lexerr] errors.angularjs.org/1.6.3/$parse/……=s%200-0%20%5B%5E%5D&p2=%5E%5B0-9%5D%7B1%2C4%7D(.%5B0-9%5D%5B0-9%5D)%3F%24
Really strange. How about just in a browser?
well for ng-pattern the format is ng-pattern="/^[0-9]{1,4}(.[0-9][0-9])?$/g" so it works great. thanks.
@SebastianProske just tested 1a22 with ng-pattern and it was invalid as expected.
Ah yes thanks Sebastian. Its a nasty feature of regex that in different versions, the parentheses, dots etc have to be escaped or not escaped. Sorry. I will add to answer. Turns out (by chance!) that I got it right for Itsik's case but your point is important for others.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.