1

I am adding a validation on a text box for decimal number (4,2). i tried below code, it works after the decimal point (meaning it's restricting user inputing more than 2 digits after decimal point) but it doesn't restrict user inputing more than 4 digits before the decimal point.

ng-pattern-restrict="^[0-9]{0,4}+(.[0-9]{0,2})?$"

  • Valid input: 10.20
  • Valid input: 1234.23
  • Invalid input: 123456.23
  • Invalid input: 1234.23456

1 Answer 1

3

The {0,4} means "0 to 4 of the proceeding pattern". The + means "one or more of the proceeding pattern" and the . means "any character".

So it sounds like you need to drop the + (you already have the count specified in {0,4}) and escape the . to match the literal decimal point.

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

  • 10.20 matches
  • 1234.23 matches
  • 123456.23 no match
  • 1234.23456 no match

Keep in mind this is not a universally acceptable method of validating decimals. Different regions use different symbols for the decimal point, for example.

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

4 Comments

Doesn't the the + mean possessive here. However no idea if modern JS supports those
Oh yes, I think you're quite right. And perhaps it's unsupported.
The above one is working thank you Health Raftery, I want to allow comma anywhere before the decimal point. Can you help me where i can add comma. Ex: 10,20,000.00
That's quite a different request. It would be irresponsible to answer it in a comment. Remember the [] means match any of the enclosed character sets, so you can just put a comma next to 0-9. But that doesn't solve your longer number problem. Try out some regex and ask another question if you get stuck.

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.