In this article I will explain a simple tutorial with an example, how to use the ng-pattern-restrict directive in AngularJS.
The ng-pattern-restrict directive is used to restrict the user input by disabling the invalid characters with the help of Regular Expression patterns in AngularJS.
 
 
AngularJS: ng-pattern-restrict Tutorial with example
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
Along with the AngularJS JavaScript file, ng-pattern-restrict.min.js file also needs to be inherited in order to perform AlphaNumeric validation.
The following AngularJS App makes use of ngPatternRestrict module.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
The Regular Expression pattern which needs to be allowed need to be set after negating it in the pattern attribute and also the ng-pattern-restrict attribute needs to be specified which will specify that it will be prevent all characters except the ones specified in the Regular Expression pattern.
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/AlphaGit/ng-pattern-restrict/master/src/ng-pattern-restrict.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', ['ngPatternRestrict'])
        app.controller('MyController', function ($scope) {
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        Passport Number:
        <input type="text" id="txtPassportNumber" pattern="^[A-Za-z0-9]+$" ng-pattern-restrict />
    </div>
</body>
</html>
 
 
Demo
 
 
Downloads