In this article I will explain with an example, how to perform Aadhaar Number validation using
Regular Expression in Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The following Form consists of:
TextBox – For capturing Aadhaar number.
Label – For showing error message.
Button – For validating Aadhaar number.
The Button has been assigned with the Click event handler.
Namespaces
You will need to import the following namespace.
C#
using System.Text.RegularExpressions;
VB.Net
Imports System.Text.RegularExpressions
Regular Expression (Regex) to validate Aadhaar Number
Regular Expression (Regex)
^([0-9]{4}[0-9]{4}[0-9]{4}$)|([0-9]{4}\s[0-9]{4}\s[0-9]{4}$)|([0-9]{4}-[0-9]{4}-[0-9]{4}$)
Explanation
The following Aadhaar Number formats will be termed as valid.
1. 12 digits without space. Ex: 123456789012
2. White space after every 4th digit. Ex: 1234 5678 9012
3. Hyphen (-) after every 4th digit. Ex: 1234-5678-9012
Example
When the
Validate Button is clicked, the value of the TextBox is validated against the
Regular Expression (Regex) and if invalid, the error message is displayed.
C#
private void OnValidate(object sender, EventArgs e)
{
lblError.Hide();
Regex regex = new Regex(@"^([0-9]{4}[0-9]{4}[0-9]{4}$)|([0-9]{4}\s[0-9]{4}\s[0-9]{4}$)|([0-9]{4}-[0-9]{4}-[0-9]{4}$)");
if (!string.IsNullOrEmpty(txtAadhaarNumber.Text.Trim()))
{
if (!regex.IsMatch(txtAadhaarNumber.Text.Trim()))
{
lblError.Text = "Invalid Aadhaar Number";
lblError.Show();
}
}
else
{
lblError.Text = "Aadhaar Number is required";
lblError.Show();
}
}
VB.Net
Private Sub OnValidate(sender As Object, e As EventArgs) Handles btnValidate.Click
lblError.Hide()
Dim regex As Regex = New Regex("^([0-9]{4}[0-9]{4}[0-9]{4}$)|([0-9]{4}\s[0-9]{4}\s[0-9]{4}$)|([0-9]{4}-[0-9]{4}-[0-9]{4}$)")
If Not String.IsNullOrEmpty(txtAadhaarNumber.Text.Trim()) Then
If Not regex.IsMatch(txtAadhaarNumber.Text.Trim()) Then
lblError.Text = "Invalid Aadhaar Number"
lblError.Show()
End If
Else
lblError.Text = "Aadhaar Number is required"
lblError.Show()
End If
End Sub
Screenshots
Invalid Value
Valid Value
Demo
Downloads