OdeToCode IC Logo

Validating Phone Numbers with Extensions in ASP.NET

Saturday, October 2, 2004
In Visual Studio .NET, we are fortunate to have Form Validation controls which do an excellent job for us. But, with Regular Expression Validators, Microsoft has only given us a taste of the real power behind this control. To be able to take full advantage of the Regular Expression Validator control requires some “programming”. Here is a simple example: When we want to validate a U.S. phone number, the Regular Expression validates the area code, a three digit number, a “dash”, and then a four digit number. This works fine if we were designing a web app for home use, but what about a business application where we need phone numbers with extensions? This is where the “programming” comes in. I have taken care of the phone number + extension issue for you.

This is what your ValidationExpression property should look like:  

((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}( x\d{0,})?

 Copy and paste this string into the ValidationExpression property of your Regular Expression Validator control. What I did was add “( x\d{0,})?” to the end of the string (without the quotes) that Microsoft provided for us. My example allows a user to enter a phone number with an extension formatted as: (770)123-4567 x1234. If you prefer to use “ext” for extension, simply edit the above string and replace “x” with “ext”. Make sure that your database field is big enough to accommodate the entire phone number and extension – at least varchar(25) in our case.

 

So how did I figure out what characters to use to create this validation string? It’s called Regular Expressions. Check out or search for this excellent tutorial on Microsoft’s MSDN site: Regular Expressions in ASP.NET

 

by Carl Ernest