Friday, October 9, 2009

function to format phone number field in form

Needed to format a phone number field as soon as the person typed it into the form, I like this solution:

(tag) script (endtag)
function formatPhone(fld)
{
var ph = fld.value.replace(/[^\d]/g, "" ); // zap all except digits
// if user entered the leading 1, just zap it
if ( ph.length == 11 && ph.charAt(0) == "1" ) ph=ph.substring(1);
if ( ph.length != 10 )
{
alert("Sorry, '" + fld.value + "' is not valid phone number");
return false;
}
fld.value = "(" + ph.substring(0,3) + ") " + ph.substring(3,6) + "-" + ph.substring(6);
return true;
}
(endtag)script(tag)

and it is called by:
onchange="formatPhone(this);" - or it could be used during validation....

No comments:

Post a Comment