All Things Techie With Huge, Unstructured, Intuitive Leaps

Javascript - How To Format a Telephone Number

This is quite a common problem. You have an user input table on your html or jsp page and you want to make sure that it is numbers only, has the area code, and is in a consistent format when you put it into the database. I downloaded some javascript to do just that and it worked fine for numbers that you typed in using the numbers on the keyboard. But when you used the numeric keypad on the keyboard, or a USB external keypad, it failed. The keypad, instead of putting numbers, put junk into it.

So this is how I solved it. I created a javascript file called phone.js. This is the contents:

function formatPnum(phonenum, textbox) {
var regexObj = /^(?:\+?1[-. ]?)?(?:\(?([0-9]{3})\)?[-. ]?)?([0-9]{3})[-. ]?([0-9]{4})$/;
if (regexObj.test(phonenum)) {
var parts = phonenum.match(regexObj);
var phone = "";
if (parts[1]) {
phone += "(" + parts[1] + ") "; }
phone += parts[2] + "-" + parts[3];
textbox.value = phone;
}
else {
//invalid phone number
alert('Please enter a proper phone number');
textbox.value = '';
}
return false;
}

Then at the top of the html page, I added the following script tag:

(script type="text/javascript" src="phone.js" /)

Note: I used "(" and ")" instead of "<" and ">" because this blog actually parses it as real HTML. Then, everywhere I needed a phone number, I added this to the tag (in this case for a fax number):


Fax (Area Code + #)
(input type="text" name="fax" onfocus="this.value='';" onmouseout="javascript:return formatPNum(this.value, this);")


Note: I used "(" and ")" instead of "<" and ">" because this blog actually parses it as real HTML.
You will note, that I have an onfocus event. When the user clicks on it, the previous number or whatever is in the input box goes away. Then the user enters the number. If any part of it fails (like he adds a letter), it fails and the alert shows that there is an error. There is no input displayed. However, if the user enters a three digit area code and a seven digit number, the phone number is automagically formatted into (123) 456-7890.

Piece of cake. Hope this helps.

No comments:

Post a Comment