Validating Phone Number In C#

valid phone number in c#

Today I will teach you how to create a program that will validate phone number using C#.

Let’s start this tutorial!

1. Create a Windows Form Application for this tutorial by following steps in Microsoft Visual Studio 2019: Go to File, click New Project, and choose Windows Application.

2. Add one TextBox named TextBox1 which will be used to input the phone number. Add also one Button named Button1 to know if the phone number we input is valid or not. Design your interface like this one below:


3. Import this namespace and put this at the topmost part of your code tab:

  1. using System.Text.RegularExpressions;

The namespace above provides regular expression functionality that may be used for any platform or language that runs within the Microsoft .NET Framework and it defines whether a particular string conforms to a regular expression pattern.

4. Put this code for the Button1_Click. This will trigger to decide whether the phone number is valid or not.

private void Button1_Click(System.Object sender, System.EventArgs e)
    Regex phonenumber = new Regex("\d{4}-\d{3}-\d{4}");
    if (phonenumber.IsMatch(TextBox1.Text))
        MessageBox.Show("Valid phone number!");
        MessageBox.Show("Not Valid phone number!");

We initialized phonenumber to hold the values of our regular expression (“d{4}-d{3}-d{4}”) which means it has a digit of 4 – digit of 3 – and digit of 4. The “d” there means the number of digits inside the expression.

Then, we use the IsMatch function to compare the value inputted in our textbox to the regular expression of the phonenumber variable. It needs to match with the expression of 0000-000-0000 format. If match, it will display “Valid phone number!” otherwise “Not Valid phone number!“.


Valid phone number


Invalid phone number


Sharing is caring!

Facebook Comments

Leave a Reply