Validating User Input Using Regular Expression With C#

Ninety-nine percent of software applications require data which are entered by users, for example when you want to create an email account (Hotmail, Gmail ...Etc.), you see a form contains a number of fields and  each one of these fields has to be filled in with specific data such as Email, Zip code, phone number and a password with specific conditions. As a developer you create a form like this and put a label beside each field to tell the user that you should enter your zip code in this field, but actually not all the users follow the labels and enter what you are waiting for, sometimes one of the users will enter a fake email address or even enter some letters that don’t refer to anything like “abcdef” as Phone number, this mistake will lead to some problems. After adding this value to the database and dealing with it in another place, for example if you want to send this user an sms message, in this situation your system will try to send a message to this phone number “abcde”, it’s not only a fake phone number it’s something not related even to numbers. So as a software developer you should know that there are two types of users,

  • Innocent users
    This type of users use your system to get some tasks accomplished by your software so if you ask the user for his/her email address, these users will enter their real email addresses, but in the real world these are not the majority of the all users, there is another type called,

  • Malicious users
    This type always try to enter fake data or try to make mistakes to see the results or even to get some information about how your system is working, sometimes these users fill in a field with a specific phases which will lead to big problems such as SQL Injection, to read about SQL Injection https://www.w3schools.com/sql/sql_injection.asp

Also imagine that you have a web application and there is a form to add a new article, this form contains a text box to enter the title of the article which will render as a label when the users will read the article, if one of the users write “<a href=”dangerous link”>Some text</a>” in the field, this will cause a big problem because when the users will open the article instead of seeing the title they will see a link that is maybe a dangerous link.

So checking what users write in your app fields is very important aspect to build a robust and secure apps.

In this article I’ll try to explain what regular expression is and how you can use its class in your C# app to validate a user input.

What is regular expression?

A regular expression is a specific pattern used to parse and find matches in strings. A regular expression is sometimes called regex or regexp.

Example

This pattern “^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$ “ matches an email address, so you can use this pattern to validate if a specific string is equals to a valid email address or not.

Fortunately you don’t have to create these patterns, you can find any pattern here, http://regexlib.com/Search.aspx

Implement user validation using regex and C#

In this example I’ll show you how to use regex class to validate an email, zip code and phone number field within a windows form app.

You can find the regex class in the System.Text.RegualExpressions namespace

So let’s start,

Note

In this example I use Visual Studio 2017 Windows Forms application.

  1. Open visual studio and click on new project button

  2. Choose Windows Forms Template and name the project as you want

    C#

  3. Design a form like this form,

    C#

  4. double click on the check button to create the click button event handler in the form’s code behind file

In the Form1.cs code behind file write the following code (Code is self-explanatory)

  1. using System;  
  2. using System.Windows.Forms;  
  3. // Add the following namespace   
  4. using System.Text.RegularExpressions;   
  5.   
  6. namespace RegualtExpression  
  7. {  
  8.     public partial class Form1 : Form  
  9.     {  
  10.         public Form1()  
  11.         {  
  12.             InitializeComponent();  
  13.         }  
  14.   
  15.         private void button1_Click(object sender, EventArgs e)  
  16.         {  
  17.             // Create string variables that contain the patterns   
  18.             string emailPattern = @"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"// Email address pattern  
  19.             string zipCodePattern = @"^\d{3}\s?\d{3}$";  
  20.             string phonePattern = @"^[2-9]\d{2}-\d{3}-\d{4}$"// US Phone number pattern   
  21.   
  22.             // Create a bool variable and use the Regex.IsMatch static method which returns true if a specific value matches a specific pattern  
  23.             bool isEmailValid = Regex.IsMatch(txtEmail.Text, emailPattern);  
  24.             bool isZipValid = Regex.IsMatch(txtZipCode.Text, zipCodePattern);  
  25.             bool isPhoneValid = Regex.IsMatch(txtPhone.Text, phonePattern);  
  26.   
  27.             // Now you can check the result   
  28.             if(!isEmailValid)  
  29.             {  
  30.                 MessageBox.Show("Please enter a valid email");  
  31.             }  
  32.   
  33.             if(!isZipValid)  
  34.             {  
  35.                 MessageBox.Show("Please enter a valid zip code");   
  36.             }  
  37.   
  38.             if(!isPhoneValid)  
  39.             {  
  40.                 MessageBox.Show("Please enter a valid phone number");   
  41.             }  
  42.   
  43.         }  
  44.     }  
  45. }  

Now you can fill the fields then click check button, if there is any invalid data a message box will appear and tell you.

You can use this technique in any type of .Net apps (ASP.Net, Xamarin, WPF, UWP…)


Similar Articles