US phone number validation by adding hypen automatically using javascript

JavaScript Add comments

The following code will validate the US phone number format. It will not check for open and closing brackets. it will validate the following format xxx-xxx-xxxx.

Besides it will not allow any other characters other than numbers and hypen to be typed. if any other character is typed in then it is removed using the regular expression in the script.

This script was created for an instant purpose and i may expand it so that will have full control on the keypress.

I have called a function whichkey to find the keycode which is a cross browser code. Each browser handles event differently so we need to find the char code number using a cross browser function and here that is whichkey.

<script type="text/javascript">
function mask(e,f){
	var len = f.value.length;
	var key = whichKey(e);
	if(key>47 && key<58)
		if( len==3 )f.value=f.value+'-'
		else if(len==7 )f.value=f.value+'-'
		else f.value=f.value;
		f.value = f.value.replace(/[^0-9-]/,'')
		f.value = f.value.replace('--','-')
function whichKey(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	return code
//	return String.fromCharCode(code);
<input type="text" name="phone" id="phone" 
onkeydown="mask(event,this)" onkeyup="mask(event,this)" 
maxlength="12" />


with the above code you can add your own code to make it more useful to you. I had made a very simple attempt to do a validation.

2 Responses to “US phone number validation by adding hypen automatically using javascript”

  1. chinnathambi Says:

    nice work dude.

  2. Kadir Says:

    Hi; i need “(xxx)xxx-xxxx” this format but i dont know how i can. Can you help me?

Leave a Reply

Entries RSS