Formatting Phone number of textbox on blur javascript


String.prototype.isPhoneNumber = function()
{
   return /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/.test(this);
}

function formatPhone(theField)
{
 if (theField.value.length > 0)
 {
   var Phone = theField.value.replace(/\D/g,"");
   if (Phone.length == 10)
   {
     theField.value = "(" + Phone.substring(0,3) + ")" + Phone.substring(3, 6) + "-" + Phone.substring(6, 10);
   }
   else if ((Phone.length == 11) && (Phone.substring(0,1) == "1"))
   {
     theField.value = "(" + Phone.substring(1,4) + ")" + Phone.substring(4, 7) + "-" + Phone.substring(7, 11);
   }
   if (theField.value.isPhoneNumber() == false)
   {
     alert(theField.value + " is an Invalid Phone Number, please try again...");
     theField.focus();
     theField.select();
   }
 }
}

2 thoughts on “Formatting Phone number of textbox on blur javascript

  1. Magnificent goods from you, man. I’ve understand your stuff previous to and you’re just too excellent.

    I actually like what you have acquired here, certainly like what you’re saying and the way in which you say it. You make it entertaining and you still take care of to keep it wise. I can’t wait
    to read much more from you. This is actually a terrific website.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s