Ninety-nine percent of software applications require data that are entered by users, for example when you want to create an email account (Hotmail, Gmail ... etc..), you see a form containing 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 all users, there is another type called.
- Malicious users: This type always tries to enter fake data or 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 phase 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 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 a very important aspect of building 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 equal 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 the 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.
- Open Visual Studio and click on the new project button.
- Choose Windows Forms Template and name the project as you want.
- Design a form like this form.
- double click on the check button to create the click-button event handler in the form’s code behind the file.
In the Form 1.cs code-behind file write the following code (Code is self-explanatory).
using System;
using System.Windows.Forms;
// Add the following namespace
using System.Text.RegularExpressions;
namespace RegualtExpression
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Create string variables that contain the patterns
string emailPattern = @"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"; // Email address pattern
string zipCodePattern = @"^\d{3}\s?\d{3}$";
string phonePattern = @"^[2-9]\d{2}-\d{3}-\d{4}$"; // US Phone number pattern
// Create a bool variable and use the Regex.IsMatch static method which returns true if a specific value matches a specific pattern
bool isEmailValid = Regex.IsMatch(txtEmail.Text, emailPattern);
bool isZipValid = Regex.IsMatch(txtZipCode.Text, zipCodePattern);
bool isPhoneValid = Regex.IsMatch(txtPhone.Text, phonePattern);
// Now you can check the result
if (!isEmailValid)
{
MessageBox.Show("Please enter a valid email");
}
if (!isZipValid)
{
MessageBox.Show("Please enter a valid zip code");
}
if (!isPhoneValid)
{
MessageBox.Show("Please enter a valid phone number");
}
}
}
}
Now you can fill in the fields and then click the 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 app (ASP.Net, Xamarin, WPF, UWP…).