Java RegEx – Validate Aadhar Card Number example shows how to validate Aadhar card numbers using Java regular expression pattern.
How to validate the Aadhar card number using regex in Java?
Before we get into how to validate the Aadhar card number using regex, we first need to understand what is it and how the Aadhar card number is generated.
The Aadhar card number is a 12 digit unique identification number and it is issued to individuals by the Unique Identification Authority of India commonly known as UIDAI.
The Aadhar number is a 12 digit unique number. The first 11 digits are random and the last one digit is the checksum for the first 11 digits. Additionally, the Aadhar number never starts with 0 or 1, at least as of now.
Here is the regex pattern to include these rules.
1 |
^[2-9][0-9]{11}$ |
Where,
1 2 3 4 |
^ - Start of the string [2-9] - Any digit between 2 and 9 [0-9]{11} - Any digit between 0 to 9 11 times $ - End of the string |
Let’s try this regex against some sample numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.javacodeexamples.regex; public class RegExValidateAadharCardNumber { public static void main(String[] args) { String[] strAadharNumbers = { "91112222333", "9111222233333", "1111222233a", "011122223333", "111122223333", "222233334444" }; String strPattern = "^[2-9][0-9]{11}$"; for(String strNumber : strAadharNumbers) { System.out.println( strNumber + " => " + strNumber.matches(strPattern)); } } } |
Output
1 2 3 4 5 6 |
91112222333 => false 9111222233333 => false 1111222233a => false 011122223333 => false 111122223333 => false 222233334444 => true |
The first two numbers are not 12 in length, so they are not valid. The third number contains the character “a” which is not allowed. The fourth number starts with 0 and fifth number starts with 1, so they are not valid as well.
Sometimes the number is entered in group of 3 having 4 digits each like ‘XXXX XXXX XXXX”. In this case, you might want to remove spaces from the original number before validating it with the regular expression. You can use the replace
method to remove the spaces as given below.
1 2 3 |
for(String strNumber : strAadharNumbers) { System.out.println( strNumber + " => " + strNumber.replace(" ", "").matches(strPattern)); } |
Finally, if you are using JavaScript, jQuery, or any other front-end library, you can easily convert the regex pattern to Javascript as well.
This example is a part of the Java RegEx tutorial.
Please let me know your thoughts in the comments section below.