ngPattern adds the pattern validator
to ngModel
.
It is most often used for text-based input
controls, but can also be applied to custom text-based controls.
The validator sets the pattern
error key if the ngModel.$viewValue
does not match a RegExp which is obtained by evaluating the Angular expression given in the
ngPattern
attribute value:
^
and $
characters. For instance, "abc"
will be converted to new RegExp('^abc$')
.g
flag on the RegExp, as it will cause each successive search to
start at the index of the last search's match, thus not taking the whole input value into
account.
pattern
attribute is used, with two
differences:
ngPattern
does not set the pattern
attribute and therefore HTML5 constraint validation is
not available.
ngPattern
attribute must be an expression, while the pattern
value must be
interpolated.
<ANY>
...
</ANY>
<script>
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.regex = '\\d+';
}]);
</script>
<div ng-controller="ExampleController">
<form name="form">
<label for="regex">Set a pattern (regex string): </label>
<input type="text" ng-model="regex" id="regex" />
<br>
<label for="input">This input is restricted by the current pattern: </label>
<input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
<hr>
input valid? = <code>{{form.input.$valid}}</code><br>
model = <code>{{model}}</code>
</form>
</div>