In this article I will explain with an example, how to implement Indian PAN Card Number validation in AngularJS.
Validating PAN Card Number using ng-pattern and Regular Expressions in AngularJS
The following HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The AngularJS app HTML DIV consists of an HTML Form with a TextBox to be validated, two HTML SPAN elements for displaying the error message for Required and PAN Card Number validations and a HTML Button.
The Form
The HTML DIV consists of an HTML Form which has been created using following directives.
ng-submit - The ng-submit AngularJS directive which has been set with the expression MyForm.$valid, which means the Form will be submitted only if the $valid property of the Form is TRUE.
novalidate – It is an HTML5 attribute which directs the Browser to disable the HTML5 validations for the particular Form.
TextBox (INPUT)
required – It is an HTML5 attribute which is used to specify that the TextBox cannot be kept empty during Form submission.
SPAN
ng-show – The ng-show AngularJS directive will make the HTML SPAN visible only when the expression to be tested returns TRUE.
The first HTML SPAN will be visible when the Required validation for the PANCard TextBox is failing while the second HTML SPAN will be visible when the Regular Expressions (Regex) pattern validation for the PANCard TextBox is failing.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) { });
</script>
<div ng-app="MyApp" ng-controller="MyController">
<form name="MyForm" ng-submit="MyForm.$valid" novalidate=novalidate>
PAN Card:
<input type="text" ng-model="PANCard" name="PANCard" required=required
ng-pattern="/^([A-Z]){5}([0-9]){4}([A-Z]){1}$/" class="PAN" />
<span class="error" ng-show="MyForm.PANCard.$error.required">PAN Number is required</span>
<span class="error" ng-show="MyForm.PANCard.$error.pattern">Invalid PAN Number</span>
<hr/>
<button type="submit">Submit</button>
</form>
</div>
CSS Class
The following CSS classes are used.
1. error – It will apply RED color to the error message.
2. PAN Card – It will force the letters to be UPPER case.
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
.error { color: Red; }
.PAN { text-transform: uppercase; }
</style>
Screenshots
Invalid PAN Card Number
Valid PAN Card Number
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads