In this article I will explain with an example, how to perform AlphaNumeric validation i.e. allow only Alphabets and Numbers in TextBox using Regular Expressions in AngularJS.
The AlphaNumeric validation will be performed with the help of ngPatternRestrict module which uses Regular Expressions for restricting characters in TextBox in AngularJS.
Implementing AlphaNumeric Validation in TextBox using AngularJS
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.
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