Phone and ZIP format checker examples from C# .NET
December 16, 2014 1 Comment
It’s a common task to check the validity of an input in any application. Some inputs must follow a specific format, like phone numbers and ZIP codes. Here come two regular expression examples that will help you with that:
private static bool IsValidPhone(string candidate)
{
return Regex.IsMatch(candidate, @"^\(?\d{3}\)?[\s\-]?\d{3}\-?\d{4}$");
}
The above regular expression will return true for the following formats:
- (xxx)xxx-xxxx: (123)456-7890
- (xxx) xxx-xxxx: (123) 456-7890
- xxx-xxx-xxxx: 123-456-7890
- xxxxxxxxxx: 1234567890
Let’s now see a possible solution for a US ZIP code:
private static bool IsValidZip(string candidate)
{
return Regex.IsMatch(candidate, @"^\d{5}(\-\d{4})?$");
}
This function returns true for the following formats:
- xxxxx-xxxx: 01234-5678
- xxxxx: 01234
View all posts related to string and text operations here.
cool helper code thanks for sharing