In this article I will explain with an example, how to implement Indian Passport Number validation using Regular Expression (Regex) in jQuery.
HTML Markup
The following HTML Markup consists of an HTML TextBox, SPAN and a Button.
Passport Number:
<input type="text" id="txtPassportNumber" />
<span id="lblError" class="error">Invalid Passport Number.</span>
<hr/>
<input type="button" id="btnSubmit" value="Submit" />
Validating Passport 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 Passport Number TextBox is referenced and its value is tested using a Regular Expression.
The following conditions must satisfy for an Indian Passport Number to be termed as valid.
1. It should be eight characters long.
2. The first character should be an upper case alphabet with A-Z excluding Q, X, and Z.
3. The second character should be any digit. 1-9.
4. The third character should be any digit. 0-9.
5. The next character should be zero or one white space character.
6. The next four characters should be any digit. 0-9.
7. The last character should be any digit. 1-9.
Examples: A2096457, A20 96457
<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 = /^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$/;
if (regex.test($("#txtPassportNumber").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. passport – 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; }
.passport { 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