JavaScript Format phone number
12.09.07
Example
The user should be able to enter a phone number in many common formats (1(555) 555-5555 or 555.555.5555 or 555-555-5555 etc.). Once focus leaves the input field the phone number will be formatted (555) 555-5555.
Code
function doFormatPhone(phoneobj)
{
// set form field where phone format should take place
var gotphone = document.getElementById(phoneobj);
gotphone.onblur = function()
{
formatPhone(this);
}
}
/* Format phone number function */
function formatPhone(curPhone)
{
curPhone.value = formatPhoneStr(curPhone.value);
}
/* Returns a formatted phone number */
function formatPhoneStr(phoneNumber)
{
var tempPhone = phoneNumber.replace(/[^0-9xX]/g,"");
tempPhone = tempPhone.replace(/[xX]/g,"x");
var extension = "";
if(tempPhone.indexOf("x") > -1)
{
extension = " "+tempPhone.substr(tempPhone.indexOf("x"));
tempPhone = tempPhone.substr(0,tempPhone.indexOf("x"));
}
switch(tempPhone.length)
{
case(10):
return tempPhone.replace(/(...)(...)(....)/g,"($1) $2-$3")+extension;
case(11):
if(tempPhone.substr(0,1) == "1")
{
return tempPhone.substr(1).replace(/(...)(...)(....)/g,"($1) $2-$3")+extension;
}
break;
default:
}
return phoneNumber;
}
The function should ideally be called using unobtrusive Javascript.
window.onload = function()
{
// place any other onload functions here
// format phone number for specified input id
doFormatPhone("phone");
};
Calling the Javascript function unobtrusively allows for graceful degradation. Notice no inline Javascript in sight!
<form method="post" action="">
<fieldset>
<label for="phone">Phone Number</label>
<input type="text" name="phone" id="phone" size="14" />
</fieldset>
</form>
Credits
From YouMail.

