GST number validation is done through 2 steps
- Check if there is a character in position of a character and a number in position of a number.
- Validate the check digit that is the last character in the GST no. with Luhn mod N algorithm (https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm)
An implementation in javascript
let GST = { /* Luhn mod N algorithm https://en.wikipedia.org/wiki/Luhn_mod_N_algorithm */ chars: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', pattern: /[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9A-Za-z]{1}[Zz1-9A-Ja-j]{1}[0-9a-zA-Z]{1}/, generate_check_charcter: function(input) { factor = 2; sum = 0; n = this.number_of_valid_input_chars(); for (i = input.length - 1; i >= 0; i--) { code_point = this.code_point_from_char(input[i]); addend = factor * code_point; factor = (factor == 2) ? 1 : 2; addend = (addend / n) + (addend % n); sum += Math.floor(addend); } remainder = sum % n; check_code_point = (n - remainder) % n; return this.char_from_code_point(check_code_point); }, validate_check_character: function(input) { factor = 1; sum = 0; n = this.number_of_valid_input_chars(); for (i = input.length - 1; i >= 0; i--) { code_point = this.code_point_from_char(input[i]); addend = factor * code_point; factor = (factor == 2) ? 1 : 2; addend = parseInt(addend / n) + (addend % n); sum += addend; } remainder = sum % n; return (remainder == 0); }, number_of_valid_input_chars: function() { return this.chars.length; }, code_point_from_char: function(input) { let str = this.chars; for (let i = 0, q = str.length; i < q; i++) { if (input == str[i]) { return i; } } }, char_from_code_point: function(input) { let str = this.chars; for (let i = 0, q = str.length; i < q; i++) { if (input == i) { return str[i]; } } }, /* Function called to check if a GSTno is valid. Full GST.no is passed to the func */ is_valid_num: function(gst_no) { //Check for pattern var patt = new RegExp(this.pattern); if (!patt.test(gst_no)) { console.log('pattern wrong'); return false; } //Validate the check digit return this.validate_check_character(gst_no); } };
USAGE:
GST.is_valid_num(gst_no);
true is returned if the GST.no is valid. false if not.
Comment below if you have any questions.