Tip

Phone number validation/formatting

View member feedback to this tip.

Call this function to validate your phone number, and to format it in (###) ###-#### format. Use this code in the onBlur event of your field to call this function:


validatephone(this)

The returned formatted phone number can be changed (i.e., to ###-###-####, (###) ###.####, or any other format desired by changing the code in the switch statements.


function stripphone(Phone) {
 var fon = "";
 if (Phone != "" ) {
  for (var i = 0; i < Phone.length; i++) {
   var Chars = "0123456789";
   if (Chars.indexOf(Phone.charAt(i)) != -1) {
    fon = fon + Phone.charAt(i);
   }
  }
 }
 return fon;
};

function validatephone(Phone) {
 var tele =  stripphone(Phone.value);
 var acode="";
 var prfx="";
 var sfx="";
 if (tele != "" ) {
  switch(tele.length) {
   case 7:
    prfx=tele.substring(0,3);
    sfx=tele.substring(3);
    return prfx + "-" + sfx;
    break;
   case 10:
    acode="(" + tele.substring(0,3) + ") ";
    prfx=tele.substring(3,6);
    sfx=tele.substring(6);
    return acode + " " + prfx + "-" + sfx;
    break;
   case 11:
    acode=tele.substring(0,1) +" (" + tele.substring(1,4) + ") ";
    prfx=tele.substring(4,7);
    sfx=tele.substring(7);
    return acode + " " + prfx + "-" + sfx;
    break;
   default:
    alert("Unable to interpret Phone Number");
    Phone.focus();
    return tele;
  }
 }
};


MEMBER FEEDBACK TO THIS TIP

It seems that the formatting for this code doesn't work. Has anyone else had this problem?

—Bridget O.


Do you have comments of your own? Let us know.

This was first published in February 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.