In almost all cases, it is recommended to validate the user input for several reasons (security, reliability, etc.). In this tutorial we will find out how to write a static class that can be applied for phone number validation in C #.
Example:
In this example, we can determine if the user entered a phone number in a common format including 0123456789, 012-345-6789, (012) -345-6789, (012) 3456789, 012 345 6789, (012) 345-6789, 012.345.6789 and all associated combinations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Text.RegularExpressions; public static class PhoneNumber { // Regular expression used to validate a phone number. public const string motif = @"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"; public static bool IsPhoneNbr(string number) { if (number != null) return Regex.IsMatch(number, motif); else return false; } } public class Program { public static void Main(string[] args) { Console.WriteLine(PhoneNumber.IsPhoneNbr("012.345.6789")); } } |
If you want to use a regular expression to validate a phone number followed by the country code. For example, if you want to validate telephone numbers in France followed by +33, you can use the following regx:
1 2 3 |
string motif = @"^([\+]?33[-]?|[0])?[1-9][0-9]{8}$"; |
To check :
1 2 3 |
Console.WriteLine(PhoneNumber.IsPhoneNbr("+33298765432")); //True |