Here is a handy regular expression that will accept many variations of an U.S. phone number, allowing the input to be somewhat flexible.
^\s*[(]?\d{3}[).\-]?\s*\d{3}(\s*|[.\-]?)\d{4}\s*$
// accepted
8015551212
801 555 1212
(801)5551212
801.555.1212
801.555-1212
801-555-1212
(801)555-1212
(801) 555-1212
801-555.1212
(801 555 1212
(801 555 1212
801)5551212
// rejected
8015551212a
80155512122
801a5551212
8015;551212
(801))5551212
Just some random development ramblings mostly related to the Microsoft .NET platform.
Showing posts with label phone number. Show all posts
Showing posts with label phone number. Show all posts
Wednesday, March 30, 2016
Tuesday, June 12, 2012
Better regular expression for phone numbers (multiple formats)
I'm often surprised at how often websites only accept a specific format for phone number input (U.S.) so I thought I would post a more flexible input format.
We want to allow users to enter phone numbers in formats like:
(123) 456-7890
123-456-7890
123.456.7890
1234567890
Using a regular expression, we can allow all these formats and more.
Notice that we specify regular expression group names to easily pick up the phone number parts. In C#, this can be done like:
Finally, here the some C# code to kick things off.
We want to allow users to enter phone numbers in formats like:
(123) 456-7890
123-456-7890
123.456.7890
1234567890
Using a regular expression, we can allow all these formats and more.
^\s*[(]?(?<AreaCode>\d{3})[)]?(\s*|[.-])(?<Prefix>\d{3})(\s*|[.-])?(?<LineNumber>\d{4})\s*$
Notice that we specify regular expression group names to easily pick up the phone number parts. In C#, this can be done like:
Code:
string prefix = match.Groups["Prefix"].Value;
Finally, here the some C# code to kick things off.
Code:
Regex rePhone = new Regex(@"^\s*[(]?(?<AreaCode>\d{3})[)]?(\s*|[.-])(?<Prefix>\d{3})(\s*|[.-])?(?<LineNumber>\d{4})\s*$");
Match match = rePhone.Match("123.456.7890");
Console.WriteLine(match.Success);
Subscribe to:
Comments (Atom)
Can't RDP? How to enable / disable virtual machine firewall for Azure VM
Oh no! I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore. I did ...
-
Here is a full test program that demonstrates how to use SharpZipLib to zip an XElement into a byte array. This allows you to transfer larg...
-
Don't want Office 2007 installed on your web server to access Excel 2007 content? Here is a Visual Studio C# solution that demonstrates ...