AngularJS ng-pattern指令
AngularJS中的ng-pattern指令是用来在输入的HTML元素上为ngModel添加模式(regex模式)验证器。如果输入字段数据与ngpattern属性值中指定的Angular表达式不匹配,它被用来设置模式验证错误键。
语法:
<element ng-pattern="expression"> Contents... </element>
HTML
例子1:这个例子使用ng-pattern指令来检查密码模式。
<!DOCTYPE html>
<html>
<head>
<title>ng-pattern Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
<style>
.red {
color:red
}
.green {
color:green
}
</style>
</head>
<body ng-app="app" style="text-align:center">
<h1 style="color:green;">GeeksforGeeks</h1>
<h2 style="">ng-pattern Directive</h2>
<div ng-controller="geek">
<ng-form name="pass">
Password:<input type="password" ng-model="password"
name="password" ng-pattern="re" /><br>
<span ng-show="pass.password.error.pattern"
style="color:red">
Not valid password.
</span><br>
Confirm: <input type="password" ng-model="repass"
ng-keyup="compare(repass)" name="repass"
ng-pattern="re" /><br>
<span ng-show="isconfirm || pass.repass.dirty "
ng-class="{true:'green',false:'red'}[isconfirm]">
Password {{isconfirm==true?'':'not'}} match
</span>
</ng-form>
</div>
<script>
var app = angular.module("app", []);
app.controller('geek', ['scope', function (scope) {
scope.re = /^[a-zA-Z]\w{3,14}/;
scope.compare = function (repass) {
scope.isconfirm = $scope.password == repass ?
true : false;
}
}]);
</script>
</body>
</html>
HTML
输出:
- Invalid Input:
- 输入不匹配。
- Valid Input:
例子2:如果输入的不是数字,这个例子会显示错误。
<!DOCTYPE html>
<html>
<head>
<title>ng-pattern Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js">
</script>
</head>
<body ng-app="app" style="text-align:center">
<h1 style="color:green;">GeeksforGeeks</h1>
<h2 style="">ng-pattern Directive</h2>
<div ng-controller="geek">
<ng-form name="num">
Input Number: <input type="text" ng-model="number"
name="number" ng-pattern="re" /><br />
<span ng-show="num.number.error.pattern" style="color:red">
Input is not valid.
</span>
</ng-form>
</div>
<script>
var app = angular.module("app", []);
app.controller('geek', ['scope', function (scope) {
scope.re = /^[0-9]{1,6}$/;
}]);
</script>
</body>
</html>
HTML
输出:
- 输入是文本。
- 输入的是数字。