In this article I will explain with an example, how to implement Aadhaar Number validation using Regular Expression (Regex) in JavaScript.
HTML Markup
The following HTML Markup consists of an HTML TextBox, SPAN and a Button.
The Button has been assigned a JavaScript OnClick event handler.
Aadhaar Number:
<input type="text" id="txtAadhaar" />
<span id="lblError" class="error"></span>
<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.
Inside the ValidateAadhaar JavaScript function, the Aadhaar Number TextBox is referenced and its value is tested using a Regular Expression.
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";
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; }
Aadhaar Number validation using JavaScript and Regular Expression
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.