Regular expression for validating phone number
As we’ve repeatedly seen, parentheses are special characters in regular expressions, but in this case we want to allow a user to enter parentheses and have our regex recognize them.
Character classes allow you to match any one out of a set of characters.
New area codes that fit the rules listed earlier are made available regularly, and even if a phone number is valid, that doesn’t necessarily mean it was issued or is in active use.
is another character class, one that allows any one of three separators.
It’s important that the hyphen appears first or last in this character class, because if it appeared between other characters, it would create a range, as with .
The following layout breaks the regular expression into its individual parts, omitting the redundant groups of digits:^ # Assert position at the beginning of the string. Two other types of tokens used in this regular expression are character classes and quantifiers.
This is a textbook example of where we need a backslash to escape a special character so the regular expression treats it as literal input.
Simply the validation will remove all non-digits and permit only phone numbers with 10 digits. View the example in the browser Flowchart: Validate an international phone number with country code Now, let's see how to validate a phone number with country code, either in 24-0455-9034, 21.3789.4512 or 23 1256 4587 format.