In this article I have explained with an example, how to perform Passport Number validation using
Regular Expression in Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The following Form consists of one TextBox, two Labels and a Button control.
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 Passport Number
Regular Expression (Regex)
^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$
Explanation
The following conditions must satisfy for an Indian Passport Number to be termed as valid.
1. It should be eight characters long.
2. The first character should be an upper case alphabet with A-Z excluding Q, X, and Z.
3. The second character should be any digit. 1-9.
4. The third character should be any digit. 0-9.
5. The next character should be zero or one white space character.
6. The next four characters should be any digit. 0-9.
7. The last character should be any digit. 1-9.
Valid Examples: A2096457, A20 96457
Example
When the
Validate Button is clicked, the value of the TextBox is validated against the
Regular Expression (Regex) and if invalid, the error Label is displayed.
C#
private void OnValidate(object sender, EventArgs e)
{
lblError.Hide();
Regex regex = new Regex(@"^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$");
if (!regex.IsMatch(txtPassportNumber.Text.Trim()))
{
lblError.Show();
}
}
VB.Net
Private Sub OnValidate(sender As Object, e As EventArgs) Handles btnValidate.Click
lblError.Hide()
Dim regex As Regex = New Regex("^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$")
If Not regex.IsMatch(txtPassportNumber.Text.Trim()) Then
lblError.Text = "Invalid Passport Number"
lblError.Show()
End If
End Sub
Screenshots
Invalid Value
Valid Value
Demo
Downloads