2

I'm using regex for validating numbers in angularjs. But my code shows validation error when the number exceeds 9 digits.Could someone please help me to rectify my code such that any digits of number can be entered.

What I have tried is :

ng-pattern="/^\d{0,9}?$/"
2
  • \d{0,9}? why using ? here Commented Aug 5, 2016 at 13:10
  • @Tushar because of this? Commented Aug 5, 2016 at 13:20

4 Answers 4

3

Just remove the {0,9}? and use * instead like

/^\d*$/

{0,9} mean is any length between 0 and 9

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

2 Comments

can you tell me what should i add if i need to validate decimals too. What i tried before was like ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"
@anju Here : "/^[\d]*[\.]?[\d]*$/"
3

I suspect the problem is understanding the difference between:

  • {0,9}
  • [0-9]

{0,9} means "zero to 9 repetitions of the preceding term", which in this case means "zero to 9 digits".

[0-9] means "a character in the range 0 to 9 (inclusive)", which is the same as \d.

Try:

/^\d+$/

Which means "all numeric input" and excludes blank input.

To allow decimal input too, escape the dot and make the decimal part optional:

/^\d+(\.\d+)?$/

Which means "at least one digit, optionally followed by a dot and at least one digit".

2 Comments

Thank you for your help.What should i add if i need to validate decimals too. What i tried before was like ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"
@anju is blank input allowed too?
2

Just change the {0,9} quantifier with the *. And remove the ? -- it's useless:

ng-pattern="/^\d*$/"

For decimal values:

ng-pattern="/^\d*(\.\d+)?$/"

2 Comments

can you tell me what should i add if i need to validate decimals too. What i tried before was like ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"
I believe open quantifiers are just fine in your case: $\d*(\.\d+)?$. These result in a simple regex.
1

Use :

  "/^\d*?$/"

\d{0,9} = match 0 to 9 digits

\d* = match 0 to N digits

\d = digit : 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9

2 Comments

can you tell me what should i add if i need to validate decimals too. What i tried before was like ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"
You don't need ? when using * quantifier

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.