AngularJS入门之数据验证

AngularJS自带了对表单或控件的输入数据进行验证的功能,对于Html5的基础控件均有内建的验证器,以下列举了所有支持的验证类型:

  • email
  • max
  • maxlength
  • min
  • minlength
  • number
  • pattern
  • required
  • url
  • date
  • datetimelocal
  • time
  • week
  • month

 

AngularJS会在元素上自动添加如下样式:

  • ng-valid: 验证通过
  • ng-invalid: 验证失败
  • ng-valid-[key]: 由$setValidity添加的所有验证通过的值
  • ng-invalid-[key]: 由$setValidity添加的所有验证失败的值
  • ng-pristine: 控件为初始状态
  • ng-dirty: 控件输入值已变更
  • ng-touched: 控件已失去焦点
  • ng-untouched: 控件未失去焦点
  • ng-pending: 任何为满足$asyncValidators的情况

 

示例1:

 1 <!DOCTYPE >
 2 <html>
 3 <head>
 4     <style type="text/css">
 5         .ng-invalid.ng-dirty {
 6             border-color: #FA787E;
 7         }
 8 
 9         .ng-valid.ng-dirty {
10             border-color: #78FA89;
11         }
12 
13         .ng-pristine.ng-pristine {
14             border-color: #ffd800;
15         }
16     </style>
17 
18     <script src="/Scripts/angular.js"></script>
19     <script type="text/javascript">
20         (function () {
21             var app = angular.module('validationTest', []);
22 
23             app.controller('myController', ['$scope', function ($scope) {
24                 $scope.students = [];
25 
26                 $scope.addStudent = function (stu) {
27                     $scope.students.push(stu);
28                     $scope.stu = {};
29                 };
30             }]);
31         })();
32     </script>
33 </head>
34 <body ng-app="validationTest" ng-controller="myController">
35     <form name="myForm" ng-submit="myForm.$valid && addStudent(stu)" novalidate>
36         Name:
37         <input name="name" ng-model="stu.name" required />
38         <span ng-hide="myForm.name.$pristine || myForm.name.$valid" ng-show="myForm.name.$invalid">Name is required.</span>
39         <br />
40         Age:
41         <input name="age" ng-model="stu.age" type="number" max="200" min="1" required />
42         <span ng-hide="myForm.age.$pristine || myForm.age.$valid" ng-show="myForm.age.$invalid">Age is required and should between 1-200.</span>
43         <br />
44         Sex:
45         <select name="sex" ng-model="stu.sex" required>
46             <option value="0">Male</option>
47             <option value="1">Female</option>
48         </select>
49         <span ng-hide="myForm.sex.$pristine || myForm.sex.$valid" ng-show="myForm.sex.$invalid">Sex is required.</span>
50         <br />
51         Email:
52         <input name="email" ng-model="stu.email" type="email" />
53         <span ng-hide="myForm.email.$pristine || myForm.email.$valid" ng-show="myForm.email.$invalid">Email is not correct.</span>
54         <br />
55         Blog:
56         <input name="blog" ng-model="stu.blog" type="url" />
57         <span ng-hide="myForm.blog.$pristine || myForm.blog.$valid" ng-show="myForm.blog.$invalid">Blog is not correct.</span>
58         <br />
59         Birthday:
60         <input name="birthday" ng-model="stu.birthday" type="datetime-local" />
61         <span ng-hide="myForm.birthday.$pristine || myForm.birthday.$valid" ng-show="myForm.birthday.$invalid">Birthday is not correct.</span>
62 
63         <div>myForm.$valid is {{myForm.$valid}}</div>
64         <div>myForm.$invalid is {{myForm.$invalid}}</div>
65         <div>myForm.$pristine is {{myForm.$pristine}}</div>
66         <div>myForm.$dirty is {{myForm.$dirty}}</div>
67         <div>myForm.$submitted is {{myForm.$submitted}}</div>
68 
69         <div>myForm.age.$error is {{myForm.age.$error}}</div>
70 
71         <input type="submit" value="Submit" />
72     </form>
73     <hr />
74     <div ng-repeat="stu in students">
75         <span>Name:{{ stu.name }}</span>
76         <span>Age:{{ stu.age }}</span>
77         <span>Sex:{{ stu.sex == 0 ? "Male" : "Female" }}</span>
78         <span>Email:{{ stu.email }}</span>
79         <span>Blog:{{ stu.blog }}</span>
80         <span>Birthday:{{ stu.birthday }}</span>
81         <hr />
82     </div>
83 </body>
84 </html>

 

示例1中,首先对form添加novalidate属性来禁用form的浏览器默认验证行为:

<form name="myForm" ng-submit="myForm.$valid && addStudent(stu)" novalidate>

 

对必填的控件添加required属性:

<input name="name" ng-model="stu.name" required />

 

本例有2种验证结果展示方式:

1. 控件边框颜色变化:

本文开头已说过,AngularJS会在验证控件后自动添加内建的样式名称,因此,我们只需对这些预定义的样式名称添加实际的样式代码即可:

 1 .ng-invalid.ng-dirty {
 2     border-color: #FA787E;
 3 }
 4 
 5 .ng-valid.ng-dirty {
 6     border-color: #78FA89;
 7 }
 8 
 9 .ng-pristine.ng-pristine {
10     border-color: #ffd800;
11 }

 

2. 文字显示验证失败原因(以name控件为例):

<span ng-hide="myForm.name.$pristine || myForm.name.$valid" ng-show="myForm.name.$invalid">Name is required.</span>

 

ng-hide:当name为初始化状态或者通过验证的状态,无需显示错误信息提示;

ng-show:当name控件验证失败时,展示错误提示信息。

 

AngularJS还提供了一些内建的状态值,方便我们直接使用:

  • $dirty:内容已变更
  • $pristine:初始化状态
  • $valid:验证通过
  • $invalid:验证失败
  • $submitted:已提交
  • $error:所有验证失败的hash对象
  • $$success:所有验证通过的hash对象
  • $pending:所有pending(异步验证)的hash对象

 

form中添加ng-submit属性,并且当myForm.$valid(即myForm中包含的所有验证均通过时,该值才为true)提交表单并调用addStudent方法:

<form name="myForm" ng-submit="myForm.$valid && addStudent(stu)" novalidate>

 

这样,当在页面上填写完有效的信息后,我们就可以将学生对象添加到Controller的students中,并由于双向绑定的特性,最终将提交的信息同步展示到页面上。

 

自定义验证器

你可能也猜到了,AngularJS也为我们准备好了自定义验证的方式。AngularJS实际上是通过自定义Directive,并在link中将验证方法添加到指定控件的$validators中, 在$validators中定义的对象必须有modelValue和viewValue两个参数,AngluarJS会在底层调用$setValidity来验证它。

我们看一个简单的例子,自定义验证Directive:myInteger(my-integer),输入值必须是以“1”开头,并为3位数字。

示例2:

 1 <!DOCTYPE >
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5     <script type="text/javascript">
 6         (function () {
 7             var app = angular.module('customValidationTest', []);
 8 
 9             var INTEGER_REGEXP = /^\-?1\d{2}$/;
10             app.directive('myInteger', function () {
11                 return {
12                     require: 'ngModel',
13                     link: function (scope, elm, attrs, ctrl) {
14                         ctrl.$validators.myInteger = function (modelValue, viewValue) {
15                             if (ctrl.$isEmpty(modelValue)) {
16                                 return true;
17                             }
18 
19                             if (INTEGER_REGEXP.test(viewValue)) {
20                                 return true;
21                             }
22 
23                             return false;
24                         };
25                     }
26                 };
27             });
28 
29         })();
30     </script>
31 </head>
32 <body ng-app="customValidationTest">
33     <form name="myForm" ng-submit="myForm.$valid" novalidate>
34         My integer:<input name="myInteger" ng-model="custInt" my-integer required />
35         <span ng-hide="myForm.myInteger.$pristine || myForm.myInteger.$valid" ng-show="myForm.myInteger.$invalid">My integer is required and should be the value 1xx.</span>
36     </form>
37 </body>
38 </html>

 

修改AngularJS的内建验证器方法

当然如果你需要重写AngularJS内建的验证也是可以的。

示例3(官方Demo):

 1 <!DOCTYPE >
 2 <html>
 3 <head>
 4     <script src="/Scripts/angular.js"></script>
 5     <script type="text/javascript">
 6         (function () {
 7             var app = angular.module('modifyBuildinValidatorTest', []);
 8 
 9             app.directive('overwriteEmail', function () {
10                 var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;
11                 return {
12                     require: 'ngModel',
13                     restrict: '',
14                     link: function (scope, elm, attrs, ctrl) {
15                         // 仅当存在ngModel且存在email这个验证器的时候才替换
16                         if (ctrl && ctrl.$validators.email) {
17 
18                             // 这里将重写AngularJS默认的email验证器
19                             ctrl.$validators.email = function (modelValue) {
20                                 return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
21                             };
22                         }
23                     }
24                 };
25             });
26         })();
27     </script>
28 </head>
29 <body ng-app="modifyBuildinValidatorTest">
30     <form name="form" class="css-form" novalidate>
31         <div>
32             Overwritten Email:
33             <input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" />
34             <span ng-show="form.overwrittenEmail.$error.email">This email format is invalid!</span><br>
35             Model: {{myEmail}}
36         </div>
37     </form>
38 </body>
39 </html>

 

在创建Directive:overwriteEmail并定义它的行为时,首先判断是否当前控件存在,且控件上已定义了email这个验证器,若存在则改写其验证。

本例中,改写后的email验证,将使以@example.com为后缀的email地址才能通过验证。

 

本篇讲述了AngularJS的控件验证方式以及自定义验证器,学会了使用验证器,我们就可以控制页面输入数据的合法性了,这样,我们的页面逻辑就更加完善了。

 

参考资料

AngularJS官方文档:https://docs.angularjs.org/guide/forms

CodeSchool快速入门视频:http://campus.codeschool.com/courses/shaping-up-with-angular-js/intro

posted @ 2015-05-27 08:45 无上@诀 阅读(...) 评论(...) 编辑 收藏