AngularJS入门之数据验证

来源:互联网 发布:威锋网mac os x区 编辑:程序博客网 时间:2024/05/22 04:55

原文:http://www.it165.net/pro/html/201505/42056.html

  • 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:

      view sourceprint?
      01.1 <!DOCTYPE >
      02.2 <html>
      03.3 <head>
      04.4     <style type='text/css'>
      05.5         .ng-invalid.ng-dirty {
      06.6             border-color: #FA787E;
      07.7         }
      08.8
      09.9         .ng-valid.ng-dirty {
      10.10             border-color: #78FA89;
      11.11         }
      12.12
      13.13         .ng-pristine.ng-pristine {
      14.14             border-color: #ffd800;
      15.15         }
      16.16     </style>
      17.17
      18.18     <script src='/Scripts/angular.js'></script>
      19.19     <script type='text/javascript'>
      20.20         (function () {
      21.21             var app = angular.module('validationTest', []);
      22.22
      23.23             app.controller('myController', ['$scope', function ($scope) {
      24.24                 $scope.students = [];
      25.25
      26.26                 $scope.addStudent = function (stu) {
      27.27                     $scope.students.push(stu);
      28.28                     $scope.stu = {};
      29.29                 };
      30.30             }]);
      31.31         })();
      32.32     </script>
      33.33 </head>
      34.34 <body ng-app='validationTest' ng-controller='myController'>
      35.35     <form name='myForm' ng-submit='myForm.$valid && addStudent(stu)' novalidate>
      36.36         Name:
      37.37         <input name='name' ng-model='stu.name' required />
      38.38         <span ng-hide='myForm.name.$pristine || myForm.name.$valid' ng-show='myForm.name.$invalid'>Name is required.</span>
      39.39         <br />
      40.40         Age:
      41.41         <input name='age' ng-model='stu.age' type='number' max='200' min='1' required />
      42.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.43         <br />
      44.44         Sex:
      45.45         <select name='sex' ng-model='stu.sex' required>
      46.46             <option value='0'>Male</option>
      47.47             <option value='1'>Female</option>
      48.48         </select>
      49.49         <span ng-hide='myForm.sex.$pristine || myForm.sex.$valid' ng-show='myForm.sex.$invalid'>Sex is required.</span>
      50.50         <br />
      51.51         Email:
      52.52         <input name='email' ng-model='stu.email' type='email' />
      53.53         <span ng-hide='myForm.email.$pristine || myForm.email.$valid' ng-show='myForm.email.$invalid'>Email is not correct.</span>
      54.54         <br />
      55.55         Blog:
      56.56         <input name='blog' ng-model='stu.blog' type='url' />
      57.57         <span ng-hide='myForm.blog.$pristine || myForm.blog.$valid' ng-show='myForm.blog.$invalid'>Blog is not correct.</span>
      58.58         <br />
      59.59         Birthday:
      60.60         <input name='birthday' ng-model='stu.birthday' type='datetime-local' />
      61.61         <span ng-hide='myForm.birthday.$pristine || myForm.birthday.$valid' ng-show='myForm.birthday.$invalid'>Birthday is not correct.</span>
      62.62
      63.63         <div>myForm.$valid is {{myForm.$valid}}</div>
      64.64         <div>myForm.$invalid is {{myForm.$invalid}}</div>
      65.65         <div>myForm.$pristine is {{myForm.$pristine}}</div>
      66.66         <div>myForm.$dirty is {{myForm.$dirty}}</div>
      67.67         <div>myForm.$submitted is {{myForm.$submitted}}</div>
      68.68
      69.69         <div>myForm.age.$error is {{myForm.age.$error}}</div>
      70.70
      71.71         <input type='submit' value='Submit' />
      72.72     </form>
      73.73     <hr />
      74.74     <div ng-repeat='stu in students'>
      75.75         <span>Name:{{ stu.name }}</span>
      76.76         <span>Age:{{ stu.age }}</span>
      77.77         <span>Sex:{{ stu.sex == 0 'Male' 'Female' }}</span>
      78.78         <span>Email:{{ stu.email }}</span>
      79.79         <span>Blog:{{ stu.blog }}</span>
      80.80         <span>Birthday:{{ stu.birthday }}</span>
      81.81         <hr />
      82.82     </div>
      83.83 </body>
      84.84 </html>

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

      view sourceprint?
      1.<form name='myForm' ng-submit='myForm.$valid && addStudent(stu)' novalidate>

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

      view sourceprint?
      1.<input name='name' ng-model='stu.name' required />

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

      1. 控件边框颜色变化:

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

      view sourceprint?
      01.1 .ng-invalid.ng-dirty {
      02.2     border-color: #FA787E;
      03.3 }
      04.4
      05.5 .ng-valid.ng-dirty {
      06.6     border-color: #78FA89;
      07.7 }
      08.8
      09.9 .ng-pristine.ng-pristine {
      10.10     border-color: #ffd800;
      11.11 }

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

      view sourceprint?
      1.<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方法:
    • view sourceprint?
      1.<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:

      view sourceprint?
      01.1 <!DOCTYPE >
      02.2 <html>
      03.3 <head>
      04.4     <script src='/Scripts/angular.js'></script>
      05.5     <script type='text/javascript'>
      06.6         (function () {
      07.7             var app = angular.module('customValidationTest', []);
      08.8
      09.9             var INTEGER_REGEXP = /^-?1d{2}$/;
      10.10             app.directive('myInteger', function () {
      11.11                 return {
      12.12                     require: 'ngModel',
      13.13                     link: function (scope, elm, attrs, ctrl) {
      14.14                         ctrl.$validators.myInteger = function (modelValue, viewValue) {
      15.15                             if (ctrl.$isEmpty(modelValue)) {
      16.16                                 return true;
      17.17                             }
      18.18
      19.19                             if (INTEGER_REGEXP.test(viewValue)) {
      20.20                                 return true;
      21.21                             }
      22.22
      23.23                             return false;
      24.24                         };
      25.25                     }
      26.26                 };
      27.27             });
      28.28
      29.29         })();
      30.30     </script>
      31.31 </head>
      32.32 <body ng-app='customValidationTest'>
      33.33     <form name='myForm' ng-submit='myForm.$valid' novalidate>
      34.34         My integer:<input name='myInteger' ng-model='custInt' my-integer required />
      35.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.36     </form>
      37.37 </body>
      38.38 </html>

      修改AngularJS的内建验证器方法

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

      示例3(官方Demo):

      view sourceprint?
      01.1 <!DOCTYPE >
      02.2 <html>
      03.3 <head>
      04.4     <script src='/Scripts/angular.js'></script>
      05.5     <script type='text/javascript'>
      06.6         (function () {
      07.7             var app = angular.module('modifyBuildinValidatorTest', []);
      08.8
      09.9             app.directive('overwriteEmail', function () {
      10.10                 var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example.com$/i;
      11.11                 return {
      12.12                     require: 'ngModel',
      13.13                     restrict: '',
      14.14                     link: function (scope, elm, attrs, ctrl) {
      15.15                         // 仅当存在ngModel且存在email这个验证器的时候才替换
      16.16                         if (ctrl && ctrl.$validators.email) {
      17.17
      18.18                             // 这里将重写AngularJS默认的email验证器
      19.19                             ctrl.$validators.email = function (modelValue) {
      20.20                                 return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
      21.21                             };
      22.22                         }
      23.23                     }
      24.24                 };
      25.25             });
      26.26         })();
      27.27     </script>
      28.28 </head>
      29.29 <body ng-app='modifyBuildinValidatorTest'>
      30.30     <form name='form' class='css-form' novalidate>
      31.31         <div>
      32.32             Overwritten Email:
      33.33             <input type='email' ng-model='myEmail' overwrite-email name='overwrittenEmail' />
      34.34             <span ng-show='form.overwrittenEmail.$error.email'>This email format is invalid!</span><br>
      35.35             Model: {{myEmail}}
      36.36         </div>
      37.37     </form>
      38.38 </body>
      39.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


0 0
原创粉丝点击