Phone number validation/formatting
Call this function to validate your phone number, and to format it in (###) ###-#### format.
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.