Thursday, January 18, 2007

Improving on the ASP.Net Regular expression validator for phone numbers

When I am working on web development I often use the ASP.Net regular expression validator in order to validate phone numbers.
The validation expression for US phone numbers that is built in to Visual Studio expects phone numbers in xxx-xxx-xxxx format.
The problem with that is that you alwas have to preface the prompt for the phone number with a sentence explaining the format and even then people often mess it up and do not understand why their form does not submit.
A good solution for the problem is to wire the onkeyup event that will add the dashes in all the right places.
For example this is in ASP.Net 2.0:

<asp:textbox id="homePhoneTextBox"
runat="server" maxlength="12" onkeyup="phoneFormat(this, event)"></asp:textbox>
In asp.net 1.1 you can do it on the code behind:

in c# this whould be something like:

this.homePhoneTextBox.Attributes.Add("onkeyup", ="phoneFormat(this, event)");

Now all you need to do is handle this event with a JavaScript function that will format the phone number for the user:

function phoneFormat(sender, ev)
{
var theNumber;
var i;
theNumber = '';
for(i = 0; i < thenumber =" theNumber" keycode ="="> 0)
{
theNumber = theNumber.substring(0, theNumber.length -1);
}
if (theNumber.length > 6)
{ sender.value = theNumber.substring(0,3) + '-' + theNumber.substring(3,6) + '-' + theNumber.slice(6);
return(true);
}
if (theNumber.length > 5)
{
sender.value = theNumber.substring(0,3) + '-' + theNumber.substring(3,6)+ '-';
return(true);
}
if(theNumber.length > 3)
{
sender.value = theNumber.substring(0,3) + '-' + theNumber.slice(3)
return(true);
}
if (theNumber.length > 2)
{
sender.value = theNumber.substring(0,3)+ '-';
return(true);
}
sender.value = theNumber;
return(true);
}

Not the shortest function ever but it does the trick.
If you want to grab the file you can do it here:
http://www.shkedy.com/blogFiles/01182007/CustomValidation.js

No comments: