Every GST invoice in India carries a 15-character GSTIN, and a typo in it silently breaks the buyer's input tax credit. A regex alone catches the shape but not a mistyped digit. The 15th character is a check character, so you can catch most typos offline before the bill is saved.
Structure
| Position | Meaning | Example (27AAPFU0939F1ZV) |
|---|---|---|
| 1-2 | State code | 27 (Maharashtra) |
| 3-12 | PAN of the business | AAPFU0939F |
| 13 | Entity number for the same PAN | 1 |
| 14 | Default "Z" | Z |
| 15 | Check character | V |
The checksum
The check character uses a base-36 alphabet (0-9A-Z). Walk the first 14 characters, multiply each value by 1 or 2 alternately, add the base-36 "digits" of each product, and the check character is whatever brings the total to a multiple of 36.
using System.Text.RegularExpressions;
public static class Gstin
{
private const string Charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static readonly Regex Shape =
new(@"^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z][1-9A-Z]Z[0-9A-Z]$", RegexOptions.Compiled);
public static bool IsValid(string? input, out string error)
{
error = "";
if (string.IsNullOrWhiteSpace(input)) { error = "GSTIN is empty."; return false; }
var g = input.Trim().ToUpperInvariant();
if (g.Length != 15) { error = "GSTIN must be 15 characters."; return false; }
if (!Shape.IsMatch(g)) { error = "GSTIN format is not valid."; return false; }
int state = int.Parse(g[..2]);
if (state < 1 || state > 38 && state != 97 && state != 99)
{ error = "State code is not valid."; return false; }
if (CheckChar(g) != g[14]) { error = "GSTIN check character does not match. Please re-check the number."; return false; }
return true;
}
public static char CheckChar(string gstin)
{
int sum = 0;
for (int i = 0; i < 14; i++)
{
int value = Charset.IndexOf(gstin[i]);
int product = value * (i % 2 == 0 ? 1 : 2);
sum += product / 36 + product % 36;
}
return Charset[(36 - sum % 36) % 36];
}
}
Usage:
if (!Gstin.IsValid(txtGstin.Text, out var err))
{
MessageBox.Show(err, "Check GSTIN", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txtGstin.Focus();
return;
}
Notes from production
- Validate on save, not on every keystroke. Shop staff type fast; a red box after 3 characters is noise.
- Store it uppercase and trimmed. Mixed case breaks GSTR-1 matching later.
- The checksum is not proof of registration. It only proves the number is well-formed. Status (active/cancelled) needs the GST portal or a GSP API.
- Keep the state code list in one place. New codes do get added; 97 (Other Territory) and 99 (Centre Jurisdiction) exist too.
- Check the state code against place of supply to decide CGST+SGST vs IGST automatically.
I build Speed Plus 9, a GST billing/ERP app for Indian shops, in .NET.
Top comments (0)