AngularJS中的ng-pattern指令用于将模式(正则表达式模式)验证器添加到输入HTML元素上的ngModel中。如果输入字段数据与通过评估ngpattern属性值中指定的Angular表达式找到的RegExp不匹配,则用于设置模式验证错误键。
用法:
<element ng-pattern="expression"> Contents... </element>
范例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>
输出:
- 输入无效:
- 输入不匹配:
- 有效输入:
范例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>
输出:
- 输入为文字:
- 输入的是数字:
相关用法
- AngularJS ng-if用法及代码示例
- AngularJS ng-cut用法及代码示例
- AngularJS ng-value用法及代码示例
- AngularJS ng-src用法及代码示例
- AngularJS ng-app用法及代码示例
- AngularJS ng-csp用法及代码示例
- AngularJS ng-jq用法及代码示例
- AngularJS ng-required用法及代码示例
- AngularJS ng-bind用法及代码示例
- AngularJS ng-srcset用法及代码示例
- AngularJS ng-paste用法及代码示例
- AngularJS ng-submit用法及代码示例
- AngularJS ng-style用法及代码示例
- AngularJS ng-selected用法及代码示例
注:本文由纯净天空筛选整理自Vishal Chaudhary 2大神的英文原创作品 AngularJS | ng-pattern Directive。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。