In this article I will explain with an example, how to implement GST Number validation using Regular Expression (Regex) in jQuery.
HTML Markup
The following HTML Markup consists of an HTML TextBox, SPAN and a Button.
GST Number:
<input type="text" id="txtGSTNumber" />
<span id="lblError" class="error">Invalid GST Number.</span>
<hr />
<input type="button" id="btnSubmit" value="Submit" />
Validating GST Number using Regular Expression in jQuery
Inside the jQuery document ready event handler, the Submit Button has been assigned a jQuery Click event handler.
When the Submit Button is clicked, the GST Number TextBox is referenced and its value is tested using a Regular Expression.
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
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function () {
var regex = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/;
if (regex.test($("#txtGSTNumber").val())) {
$("#lblError").css("visibility", "hidden");
} else {
$("#lblError").css("visibility", "visible");
}
});
});
</script>
CSS Class
The following CSS classes are used.
1. error – It will apply RED color to the error message.
2. gst – It will force the letters to be UPPER case.
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
.error { color: Red; visibility: hidden; }
.gst { text-transform: uppercase; }
</style>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads