View Full Version : text field validation for phone number

06-25-2011, 05:02 AM
I have a phone number field on my form that needs validation, but I'm not sure how to code this. I have the following function to validate a first name is entered and last name. The phone number field must match a 7 digit or 10 digit(with area code)phone number. I want to be able to include paranthese and/or hyphens for the valid phone number.

function checkForm1() {
if (document.forms[0].firstname.value.length == 0) {
alert("You must put in a first name");
return false;
else if (document.forms[0].lastname.value.length == 0) {
alert("You must put in a last name");
return false;

06-25-2011, 05:14 AM
Firstly, just checking if an input is 0 length or not doesn't really validate anything except to check if "something" is entered.

For example:

if (document.forms[0].firstname.value.length == 0)

If someone enters the characters @#$%123(* for first name then the IF statement will evaluate to false and those chars will be accepted as a valid first name.

You should really check all inputs to ensure only valid chars. have been entered.

To validate a phone number you could use a regular expression to check if the inputs are digits and match whatever pattern you like to include brackets or hyphens.

There are lots of examples of validating names, phone numbers etc using regular expressions on the www.

06-25-2011, 05:17 AM
Start here. (http://www.javascriptkit.com/javatutors/re.shtml) A regex for optional parentheses or hyphens might be like
/^[\(]\d{2}[\)]\d{8}$/ ...maybe...I hate regular expressions. Something like that would allow (02)99998888 (australian number i don't know how you guys do it) or 0299998888. But google around for regular expressions to check the syntax, what I wrote is untested and probably wrong.

Old Pedant
06-25-2011, 05:54 AM
I do phone numbers this way:

var DEFAULT_AREA_CODE = "714"; // or whatever is your home area code
function validatePhone( fld )
var phone = fld.value.replace( /[^\d]/g ); // zaps *all* non-digits
// is user gave 11 digits with 1 as first digit, toss the leading 1 away:
if ( phone.length == 11 && phone.charAt(0) == "1" ) phone = phone.substring(1);
if ( phone.length != 10 || phone.length != 7 )
alert( "You must enter a 7 or 10 digit phone number");
return false;
if ( phone.length == 7 ) phone = DEFAULT_AREA_CODE + phone;
// next line is optional...it formats the number into standard form
phone = "(" + phone.substring(0,3) + ") " + phone.substring(3,6) + "-" + phone.substring(6);
fld.value = phone; // store the altered number back in place
return true;

06-25-2011, 06:23 AM
I want to be able to include paranthese and/or hyphens for the valid phone number.

You need to specify where the brackets and hyphens can go in the number.

Also, I would advise against simply deleting non valid chars. There is still a reasonable probability that the "edited" number is incorrect.

Imo it is better to make the user enter only valid chars, and thus minimise the probability of the user entering a wrong number, before the input has any chance of being accepted.

Old Pedant
06-25-2011, 07:20 AM
In the USA, it is very common for people to enter phone numbers in any of several ways:
(xxx) xxx xxxx
1 (xxx) xxx xxxx (because many people still have to dial 1 to use a long distance number)

and there are other common variations in use in different parts of the country. Some people really do simply use

Yes, you *can* insist that people enter in your personally preferred format. But it's not very user-friendly.

I figure why not allow the user to enter it in *any* format and then just reformat it the way you want.

In actual practice, this has proven enormously successful on sites that collect from dozens to thousands of phone numbers per day. The error rate is extremely low.

Things might be quite different in Australia. I have no way of knowing.

So you pays your money and makes your own choice as to whom you will listen to.

06-25-2011, 07:47 AM
Personally I wouldn't allow any characters but digits in a phone number and then check if the number of digits is in the correct range. You could also have a separate input for the area code. I suspect most of the time people enter false phone numbers anyway.

06-26-2011, 05:39 AM
okay, so I decided to use regular expressions to do this. This is the function I wrote and it seems to be working, however I don't know how to get the parenthesis included. With my function, I can enter xxx-xxx-xxxx and xxx-xxxx and both are accepted. But I can't figure out how to write the expression to accept the optional paranthesis.

function validatePhone(phonenum) {
regx = /^(\d{3}-)?\d{3}-\d{4}$/;
return regx.test(phonenum);

Philip M
06-26-2011, 10:04 AM
regx = /^\(\d{3}\)-|^(\d{3}-)?\d{3}-\d{4}$/;

If the user enters one bracket without the other the regex will of course return false. No lookahead or lookbehind is required. In any case (as the reference in the post by bullant - which he has now deleted - points out) Javascript does not support "lookbehind" although it does support "lookahead".

It may be a good idea to strip spaces:

phonenum= phonenum.replace(/\s+/g,"");

Old Pedant
06-26-2011, 11:53 PM
Ummm...no, Philip...you are missing the parens around the | choices.

I still think he's making a mistake, but I think this does what he wants:

regx = /^(\(\d{3}\)-|\d{3}-)?\d{3}-\d{4}$/;

^ ::: start
(...) ::: set of options
\(\d{3}\)- ::: one option (ddd)-
| ::: or
\d{3}- ::: other option ddd-
(...)? ::: the entire set of options is itself optional


06-27-2011, 02:33 AM
I found 42 unique, valid formats for US telephone numbers. I wrote a JavaScript function which not only checks for a valid number but also returns it in whatever format you want. The user might enter "1(810)762-3121" and you could specifiy 10-digit output and would get back "8107623121" for the result. It also handles extentions and alphabetics like 1-800-HOLIDAY for Holiday Inn.

I use it on the Sample Order Form page at my web site. Please feel free to check it out.

Philip M
06-27-2011, 08:31 AM
Ummm...no, Philip...you are missing the parens around the | choices.

Not so! Try it and you will see that it works perfectly. :)