Web Design & Development

Simple Regular Expression Phone Number Validation

Tagged with: , ,

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 helpful control for validating form inputs using a regular expression, which can be used to make sure phone numbers are entered in the exact format that you want to save.

The following example uses ASP.NET to ensure users input phone numbers using the format XXX-XXX-XXXX:

<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 as strict with your format; you can also make more complicated regular expressions using optional parentheses, spaces, and more. Instead of making an elaborate regular expression to match how you think your visitor will input their phone number, try this approach. Take the phone number input, strip out the symbols, and check for 10 numeric digits. Then if you need to save the phone number in a consistent format, build that format from the 10 digits.

The following example uses C# to validate 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 and other applications, talk to our team!