Go to home page mail me! RSS Feed

Validate a U.S Phone number

Wednesday, January 14, 2009 1:44 PM

Here is a simple function that validates a U.S phone number using regular expressions. Note the use of the static method, which prevents unnecessary object instantiation. Its all about optimize code.

public static bool IsValidPhoneNumber(string phoneNumber)
{
    string pattern = @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$";
    return Regex.IsMatch(phoneNumber, pattern);            
}

Your Comments.

No comments posted yet.

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 2 and 8 and type the answer here:

Preview Your Comment.

 
Next entries »