In this article I will explain with an example, how to perform GST (Goods and Services Tax) 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 GST number.
Label – For showing error message.
Button – For validating GST 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 GST (Goods and Services Tax) Number
Regular Expression (Regex)
^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$
Explanation
The following conditions must satisfy for a GST Number to be termed as valid.
1. It should be 15 characters long.
2. The first 2 characters should be a digit representing State Code.
3. The next 10 characters should be PAN number of the taxpayer.
4. The 13th character should be any digit (1-9) or an alphabet.
5. The 14th character should be Z by default.
6. The 15th character should be an alphabet or any digit. 0-9.
Example: 06BZAHM6385P6Z2
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]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$");
if (!string.IsNullOrEmpty(txtGSTNumber.Text.Trim()))
{
if (!regex.IsMatch(txtGSTNumber.Text.Trim()))
{
lblError.Show();
}
}
else
{
lblError.Text = "GST 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]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$")
If Not String.IsNullOrEmpty(txtGSTNumber.Text.Trim()) Then
If Not regex.IsMatch(txtGSTNumber.Text.Trim()) Then
lblError.Show()
End If
Else
lblError.Text = "GST Number is required"
lblError.Show()
End If
End Sub
Screenshots
Invalid Value
Valid Value
Demo
Downloads