When creating an online form to collect contact information, the phone number box is a field frequently requested by clients. But in order to accommodate the various formats of phone numbers that users might enter, this field must be coded to validate the data.

ASP.NET has a nice control for validating form inputs using a regular expression. You may use something like this to make sure phone numbers are entered in the exact format that you want to save them. The following ensures that the user enters the phone number in this exact format: XXX-XXX-XXXX (3 digits, dash, 3 digits, dash, 4 digits)

<asp:RegularExpressionValidator ValidationExpression=”\d{3}-\d{3}-\d{4}”ControlToValidate=”txtPhone” ID=”RegExpVal_txtPhone” runat=”server” ErrorMessage=”Invalid Format (use: XXX-XXX-XXXX)” Display=”Dynamic” />

If you don’t need to be so strict for that exact format; you may end up making more complicated regular expressions with optional parentheses, spaces, etc.

Instead of making an elaborate regular expression to match how you think your visitor will input their phone number, try a different approach. Take the phone number input and strip out the symbols and just check for 10 numeric digits. Then if you need to save the phone number in a consistent format, build that format off of the 10 digits.

To see the code in action, run the example from here.

This C# example validates U.S. phone numbers by looking for 10 numeric digits.

protected bool IsValidPhone(string strPhoneInput)
{
   // Remove anything that is not a number
   string strPhone = Regex.Replace(strPhoneInput, @"[^\d]", String.Empty);

   txtPhone2.Text = strPhone;
   
   // Check for exactly 10 numbers left over
   return (strPhone.Length == 10);
}

 

One Response


  1. samira on 07 Jun 2012

    nice it is really helpful for me


Leave your comment

*