Graphic of a lock and security fields in front of shelving.

Simple Regular Expression Phone Number Validation

When creating an online form to collect contact information, the phone number box is a field frequently requested by clients. But 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””></asp:regularexpressionvalidator>

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.

Try a different approach instead of making an elaborate regular expression for matching how you think your visitor will input their phone number. 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 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);

For help with data validation, ask how we can help with your project.