Home > Back-end >  Validate number with optional plus in angular
Validate number with optional plus in angular

Time:01-22

I'm trying to validate mobile number between 10 to 12 digits with optional sign

Validators.pattern("^(( ?))?[0-9]{12}$")

but when i enter plus then it is not validation properly.

CodePudding user response:

Maybe try "^[0-9]{10,12}$" or "^\d{10,12}$" ?

CodePudding user response:

this your regex:

 ^\ ?\d{10,12}$

because is part of regex syntex you must exclude it by adding \ before, and the ? symbol mean that is optional

CodePudding user response:

-UPDATE-

The issue is with the " " character in the regular expression. In a regular expression, the " " character is a special character that means "one or more of the preceding character." In this case, the " " character is not preceded by any other character, so the regular expression is saying "one or more of nothing." To fix the issue, you should escape the " " character with a "", so that it is treated as a literal " " character instead of a special character.

Try this regular expression instead: "^(( )?[0-9]{10,12})$"

Also, you should use "?" or {0,1} after the " " sign if you want it to be optional.

So the final regular expression should be like this: "^(( )?[0-9]{10,12})$"

-END OF UPDATE-

The issue is with the pattern you are using. The " " character has a special meaning in regular expressions, so you need to escape it in order for it to be treated as a literal character. You can use the "" character to escape it, like this:

Validators.pattern("^(( )?[0-9]{10,12})$")

This pattern will match a string that starts with an optional " " character, followed by 10 to 12 digits.

  • Related