The plug-in does the following
1. Formats the number to (NPA)-NXX-XXXX as it is typed
2. It will not allow you to enter special characters or non-number in the textbox.
3. It will validate that you can enter only 10 digits
4. This plug-in as of now does not support chaining as I did not see a need.
Plug-in code : Save this as whatever JS file you need it to be - I have used jquery.usphone.js in the HTML
(function( $ )
{
// This function formats a text field to a US
// phone number as the user types the information.
$.fn.usphone = function()
{
this.keyup(function()
{
var curchrindex = this.value.length;
var curval = $(this).val();
var strvalidchars = "0123456789()-";
for (i =0; i < this.value.length; i++)
{
var curchar = curval[i];
if (strvalidchars.indexOf(curchar) == -1)
{
//delete the character typed if this is not a valid character.
$(this).val(curval.substring(0, i) + curval.substring(i+1, this.value.length));
}
}
// Insert formatting at the right places
if (curchrindex == 3)
{
$(this).val("(" + curval + ")" + "-");
}
else if (curchrindex == 9)
{
$(this).val(curval + "-");
}
//Do not allow more than 15 characters including the brackets and the "-"
if (curchrindex == 15)
{
//delete the last character typed
$(this).val(curval.substring(0, this.value.length-1 ));
}
});
};
})( jQuery );
The HTML code to use this plug-in
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="./scripts/jquery.js"></script>
<script type="text/javascript" src="./jquery.usphone.js"></script>
</head>
<body>
Please Enter a Valid US Phone number :
<input type = "text" id = "phonenumber" />
</body>
<script>
$('#phonenumber').usphone();
</script>
</html>