HTML Markup
Aadhaar Number:
<input type="text" id="txtAadhaar" />
<span id="lblError" class="error"></span>
<hr />
<input type="button" id="btnSubmit" value="Submit" onclick="ValidateAadhaar()" />
Validating Aadhaar Number using Regular Expression in JavaScript
When the
Submit Button is clicked, the
ValidateAadhaar JavaScript function is executed.
The following Aadhaar Number formats will be termed as valid.
1. 12 digits without space. Ex: 123456789012
2. White space after every 4th digit. Ex: 1234-5678-9012
3. Hyphen (-) after every 4th digit. Ex: 1234-5678-9012
Finally, if the
Aadhaar Number format is incorrect, then an
HTML SPAN element with an error message is displayed.
<script type="text/javascript">
function ValidateAadhaar() {
var aadhaar = document.getElementById("txtAadhaar").value;
var lblError = document.getElementById("lblError");
lblError.innerHTML = "";
var expr = /^([0-9]{4}[0-9]{4}[0-9]{4}$)|([0-9]{4}\s[0-9]{4}\s[0-9]{4}$)|([0-9]{4}-[0-9]{4}-[0-9]{4}$)/;
if (!expr.test(aadhaar)) {
lblError.innerHTML = "Invalid Aadhaar Number";
}
}
</script>
CSS Class
The following CSS class is used.
error – It will apply RED color to the error message.
<style type="text/css">
body {font-family: Arial; font-size: 10pt; }
.error {color: Red; }
</style>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads