Validating Phone Number

Validating Phone Number in C#

Details: Validating Phone Number

Phone number is one of the important information in any organization. Therefore, it is necessary to validate and secure the phone number in a reliable way. In this article, we will discuss how to validate a phone number in C#.

This post is centered on creating a program that can validate phone numbers using the C# programming language. We can achieve this with the following process below;

1 – We start by creating a Windows Form Application using Microsoft Visual Studio 2019
– Navigate to File
– Click on New Project
– Select Windows Application.

2 – Next, we add a TextBox and label it TextBox1 that will be used to input the phone number.
– Add a Button and label Button1; this will aid in telling us if the phone number is valid or not.
Your interface should be designed liked the image below.

Validating Phone Number in C#, c#, programming language, free download, free source code, source code, validate, valide, phone number, invalid

3 – Now, the namespace will be imported and inserted at the top part of the code.

This namespace provides regular expression functionality that can be used on any language or platform that works within the Microsoft .NET Framework and it defines if a specific string agrees to a regular expression pattern.

4 – To check the validity of a phone number, use the code below for Button1_Click.

					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 instated phonenumber to hold the values of our regular expression (“\d{4}-\d{3}-\d{4}”) and that implies it has a digit of 4 – digit of 3 – and digit of 4. The “d” there implies the number of digits inside the expression.

Then, at that point, we utilize the IsMatch function to compare the value inputted in our textbox to the regular expression of the phonenumber variable. It is necessary to match with the outflow of 0000-000-0000 format. If matched, it will show “Valid Phone Number!” or “Not Valid Phone Number!”.

Outputs: Validating Phone Number

Valid phone number: Validating Phone Number

Not Valid phone number

Recommended Tutorial: Bouncing Ball in C#

Don’t forget to share this post!

Leave a Comment

Your email address will not be published. Required fields are marked *

Related Article