With all of this in mind, let’s look at the regular expression again after breaking it into its pieces. : # Group but don't capture: [0-9] # Match a digit. ITU-T Recommendation E.123 (“Notation for national and international telephone numbers, e-mail addresses and web addresses”) can be downloaded at
Because this version is written using free-spacing style, the literal space character has been replaced with ^ # Assert position at the beginning of the string. ITU-T Recommendation E.164 (“The international public telecommunication numbering plan”) can be downloaded at RFC 5733 defines the syntax and semantics of EPP contact identifiers, including international phone numbers. Techniques used in the regular expressions in this recipe are discussed in Chapter 2.
This way after the user tabbed away from the textbox, their number would automatically be formatted.
This would need to be updated for international numbers, or to allow users to enter phone numbers using letter representation.
In a real case, this function would probably be called as part of a larger validate form function.
The idea behind this code is to make it as simple as possible for the user to correctly enter their phone number in the correct format.
Basically our validate Phone function takes an HTML text input field and a format type, strips all non-digits from the number and validates based on the cleansed string lenght.
A regular expression can easily check whether a user entered something that looks like a valid phone number.
If the phone number was invalid, we would want to return false to cancel form submission as well as informing the user of the errors of their ways.