'GST number validation in php

I am trying to implement GST validation in php.

if(!preg_match("/^([0-5]){2}([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([a-zA-Z0-9]){1}([a-zA-Z]){1}([0-9]){1}?$/", $testcase)) {
        $flag = "Invalid GST number ";
        return $flag;
    } 

1st 2 digits are state code which will be between 01 to 35, but my code will accept 01 to 55 which is wrong. Any way to validate it upto 35 only.



Solution 1:[1]

You need to break you number range into the actual digits.

The following will work

if(!preg_match("/^(0[1-9]|[1-2][0-9]|3[0-5])([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([a-zA-Z0-9]){1}([a-zA-Z]){1}([0-9]){1}?$/", $testcase)) {
    $flag = "Invalid GST number ";
    return $flag;
} 

The number regex works as follows, we split out the first 2 digit validation into 3 scenarios.We use the or operator | to split out into the scenarios.

(0[1-9]|[1-2][0-9]|3[0-5])
  • The 2 digits start with zero
    • The second digit can only be between 1 and 9
    • Allows: 01-09
  • The 2 digits start with a 1 or 2
    • Allow the second degit to be 0-9
    • Allows 10-29
  • The 2 digits start with a 3
    • Allows the second digit to be 0-5
    • Allows 30-35

Hope this helps

Solution 2:[2]

i think you should start the regex with:

/^([0-2][0-9])|(3[0-5])

edit: a flaw: this also allows 00

Solution 3:[3]

<?php 
    $gst="11ABCD2222E1EF";  
    if (!preg_match("/^([0-9]){2}([A-Za-z]){5}([0-9]){4}([A-Za-z]){1}([0-9]{1})([A-Za-z]){2}?$/", $pan)) { //GSTN validation
        echo"Invalid GSTN";
    }
    else{
        echo"Valid GSTN";
    }
?>

This code will work fine

Solution 4:[4]

if(!preg_match("/^([0-9]){2}([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}([a-zA-Z0-9]){3}$/", $gst_no)) { $gst_invalid=yes; }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JParkinson1991
Solution 2 Ivo P
Solution 3 atline
Solution 4 Ryan M