views:

226

answers:

3

What's the most efficient way to quickly check for telephone number format from a form input text?

+1  A: 

That really depends on the location. There are different conventions from place-to-place as to the length of the area code and the length of the entire number. Being more permissive would be better.

A regular expression to ensure that it is an optional '+', followed by any number of digits would be the bare minimum. Allowing optional dashes ("-") or spaces separating groups of numbers could be a nice addition. Also, what about extension numbers?

In truth, it's probably best to just check that it includes some numbers.

Gian
+7  A: 

easiest way is to strip out everything that is not a number and then count how many digits there are. That way you don't have to force a certain format on the user. As far as how many numbers you should check for...depends on if you are checking for just local numbers, US numbers, international numbers, etc...but for instance:

$number="(123) 123-1234";
if (strlen(preg_replace('~[^0-9]~','',$number)) == 10) {
  // 10 digit number (US area code plus phone number)
}
Crayon Violent
I was just writing this as we speak.
no
in other words, forcing consumers to write in the dashes and parentheses is purely for frontend/consumer-time-wasting!
ina
A + is valid if people are putting their country code in eg Ireland would be +353 21 etc
Toby Allen
A: 

If you are only dealing with U.S. phone numbers, you might follow the common UI design of using three textboxes = one for area code + second one for exchange + third one for number. That way, you can test that each one contains only digits, and that the correct number of digits is entered.

You can also use the common techniques of testing each keypress for numbers (ignoring keypresses that are not digits), and advancing to the next textbox after the required number of characters have been entered.

That second feature makes it easier for users to do the data entry.

Using separate textboxes also makes it a little easier for users to read their input, easier than, say, reading that they have entered ten digits in a row correctly.

It also avoids you having to deal with people who use different punctuation in their entries -- surrounding the area code with parentheses, using hyphens or dots between sections.

Edit: If you decide to stick with just one textbox, there are some excellent approaches to using regex in this SO question.

DOK