How to Validate Phone Number Using C# - Simple Guide
To validate a phone number in C#, use the
Regex class with a pattern that matches your phone number format. For example, use Regex.IsMatch(phone, pattern) to check if the input matches the expected phone number style.Syntax
Use the Regex.IsMatch(string input, string pattern) method to check if the phone number matches a pattern.
input: The phone number string to validate.pattern: A regular expression defining the valid phone number format.
The method returns true if the input matches the pattern, otherwise false.
csharp
bool isValid = Regex.IsMatch(phoneNumber, pattern);
Example
This example shows how to validate a US phone number format like (123) 456-7890 or 123-456-7890 using a regular expression.
csharp
using System; using System.Text.RegularExpressions; class Program { static void Main() { string[] phoneNumbers = { "(123) 456-7890", "123-456-7890", "1234567890", "123.456.7890", "123-45-6789" }; string pattern = @"^\(?\d{3}\)?[- .]?\d{3}[- .]?\d{4}$"; foreach (var phone in phoneNumbers) { bool isValid = Regex.IsMatch(phone, pattern); Console.WriteLine($"{phone} is valid? {isValid}"); } } }
Output
(123) 456-7890 is valid? True
123-456-7890 is valid? True
1234567890 is valid? True
123.456.7890 is valid? True
123-45-6789 is valid? False
Common Pitfalls
Common mistakes when validating phone numbers include:
- Using too strict or too loose regular expressions that reject valid numbers or accept invalid ones.
- Not accounting for different formats like spaces, dots, or country codes.
- Assuming all phone numbers have the same length or pattern.
Always tailor your regex to the expected phone number formats and test with real examples.
csharp
/* Wrong: Too strict pattern rejects valid formats */ string wrongPattern = "^\d{10}$"; // Only 10 digits, no separators /* Right: Allows common separators and optional parentheses */ string rightPattern = @"^\(?\d{3}\)?[- .]?\d{3}[- .]?\d{4}$";
Quick Reference
Tips for phone number validation in C#:
- Use
Regex.IsMatchfor pattern matching. - Design regex patterns to match your expected phone formats.
- Test with various valid and invalid phone numbers.
- Consider international formats if needed.
Key Takeaways
Use Regex.IsMatch with a suitable pattern to validate phone numbers in C#.
Adjust your regular expression to match the phone number formats you expect.
Test your validation with multiple phone number examples to avoid errors.
Avoid overly strict or overly loose patterns to prevent false results.