Java Reference
In-Depth Information
The actual code is very simple, but the regular expressions are tricky to create, so let's look at those in
depth starting with telephone number validation.
Telephone Number Validation
Telephone numbers are more of a challenge to validate. The problems are:
Phone numbers differ from country to country.
There are different ways of entering a valid number (for example, adding the national or inter-
national code or not).
For this regular expression, you need to specify more than just the valid characters; you also need to
specify the format of the data. For example, all of the following are valid:
+1 (123) 123 4567
+1123123 456
+44 (123) 123 4567
+44 (123) 123 4567 ext 123
+44 20 7893 4567
The variations that our regular expression needs to deal with (optionally separated by spaces) are
shown in the following table:
The international number
+ “ followed by one to three digits (optional)
The local area code
Two to fi ve digits, sometimes in parentheses (compulsory)
The actual subscriber number
Three to 10 digits, sometimes with spaces (compulsory)
An extension number
Two to fi ve digits, preceded by x, xtn , extn , pax , pbx , or
extension , and sometimes in parentheses
Obviously, there will be countries where this won't work, which is something you'd need to deal with
based on where your customers and partners would be. The following regular expression is rather com-
plex, its length meant it had to be split across two lines; make sure you type it in on one line.
^(\+\d{1,3} ?)?(\(\d{1,5}\)|\d{1,5}) ?\d{3} ?\d{0,7}
( (x|xtn|ext|extn|pax|pbx|extension)?\.? ?\d{2-5})?$
You will need to set the case-insensitive fl ag with this, as well as the explicit capture option. Although
this seems complex, if broken down, it's quite straightforward.
Let's start with the pattern that matches an international dialing code:
(\+\d{1,3} ?)?
Search WWH ::




Custom Search