当前位置:首页 >> 网络编程

AngularJS自定义表单验证功能实例详解

本文实例讲述了AngularJS自定义表单验证功能。分享给大家供大家参考,具体如下:

Angular实现了大部分常用的HTML5的表单控件的类型(text, number, url, email, date, radio, checkbox),也实现了很多指令做为验证(required, pattern, minlength, maxlength, min, max)。

在自定义的指令中,我们可以添加我们的验证方法到ngModelController的$validators对象上。为了取得这个controller对象,我们需要requirengModel指令。

在$validators对象上的每个方法都接收modelValue和viewValue两个值做为参数。在你绑定的验证方法返回一个值(true,false)之后,Angular会在内部调用$setValidity方法。验证会在每一次输入框的值改变($setViewValue被调用)或者模型的值改变。验证发生在$parsers和$formatters成功运行之后,验证不通过的项会做为ngModelController.$error的属性存储起来。

另外,在这个controller对象上,还有一个$asyncValidators对象,如果你的验证是异步的,则需要加验证附加在这个对象上,比如说用户注册时输入手机号,我们需要在后端验证该手机号是否已经注册,这个验证方法必须return一个promise对象,然后在验证通过时调用延迟对象的resolve,失败时调用reject,还未完成的异步的验证存储在ngModelController.$pending中。

例如(注意其中的user对象,只有验证通过了,才会将值绑定到模型上):

<form name="register_form" ng-submit="save()">
    <div class="form-group">
        <label for="phoneNumber">
            手机号(不能重复):
        </label>
        <input type="text" class="form-control" ng-model="user.phoneNumber" id="phoneNumber" name="phoneNumber" required phone>
    </div>
    <div class="form-group">
        <label for="username">
            用户名(必须大于五位):
        </label>
        <input type="text" class="form-control" ng-model="user.username" id="username" required username>
    </div>
    <button class="btn btn-block btn-primary" type="submit">提交</button>
</form>
<h3>用户对象</h3>
<pre>
    {{ user | json }}
</pre>
'use strict';
angular.module('app', [])
.directive('phone', function ($q, $http) {
  return {
    require: 'ngModel',
    link: function (scope, ele, attrs, ctrl) {
      ctrl.$asyncValidators.phone = function (modelValue, viewValue) {
        var d = $q.defer();
        $http.get('phone.json')
        .success(function (phoneList) {
          if (phoneList.indexOf(parseInt(modelValue)) >= 0) {
            d.reject();
          } else {
            d.resolve();
          }
        });
        return d.promise;
      }
    }
  }
})
.directive('username', function ($q, $http) {
  return {
    require: 'ngModel',
    link: function (scope, ele, attrs, ctrl) {
      ctrl.$validators.username = function (modelValue, viewValue) {
        if (modelValue) {
          return modelValue.length > 5 "htmlcode">
[
  13758262732,
  15658898520,
  13628389818,
  18976176895,
  13518077986
]

效果

AngularJS自定义表单验证功能实例详解

下面一个完整的用户注册的表单验证:

html:

<form name="register_form" novalidate>
    <div class="form-group">
        <label for="username">用户名:</label>
        <!-- ng-pattern="/PATTERN/"确保输入项符合正则 -->
        <input type="text" id="username" ng-model="user.username" class="form-control" name="username" required ng-pattern="/^[^#]*$/">
        <span class="glyphicon glyphicon-ok right" ng-show="register_form.username.$valid"></span>
    </div>
    <div class="alert alert-danger" ng-show="register_form.username.$error.pattern">
        <strong>请注意!</strong>
        用户名不能带#号。
    </div>
    <div class="alert alert-danger" ng-show="register_form.username.$error.required && register_form.username.$touched">
        <strong>请注意!</strong>
        用户名不能为空。
    </div>
    <div class="form-group">
        <label for="_password">密码:</label>
        <!-- ng-minlength="num"让密码不能小于最小长度 -->
        <input type="password" id="_password" ng-model="data._password" class="form-control" required ng-minlength="8" name="_password">
        <span class="glyphicon glyphicon-ok right" ng-show="register_form._password.$valid"></span>
    </div>
    <div class="alert alert-danger" ng-show="register_form._password.$error.minlength && register_form._password.$touched">
        <strong>请注意!</strong>
        密码长度不能少于八位。
    </div>
    <div class="alert alert-danger" ng-show="register_form._password.$error.required && register_form._password.$touched">
        <strong>请注意!</strong>
        密码不能为空。
    </div>
    <div class="form-group">
        <label for="password">确认密码:</label>
        <input type="password" id="password" ng-model="user.password" class="form-control" name="password" required pwd-repeat>
        <span class="glyphicon glyphicon-ok right" ng-show="register_form.password.$valid"></span>
    </div>
    <div class="alert alert-danger" ng-show="register_form.password.$error.pwdRepeat && register_form.password.$touched">
        <strong>请注意!</strong>
        两次输入的密码不相同。
    </div>
    <div class="alert alert-danger" ng-show="register_form.password.$error.required && register_form.password.$touched">
        <strong>请注意!</strong>
        请再次输入密码。
    </div>
    <div class="form-group">
        <label for="phone">手机号:</label>
        <div class="row">
            <div class="col-sm-10">
                <input type="num" id="phone" ng-model="user.phone" name="phone" class="form-control" required ng-minlength="11" ng-maxlength="11" phone>
            </div>
            <div class="col-sm-2">
                <button class="btn btn-default" type="button" ng-disabled="register_form.phone.$invalid">发送验证码</button>
            </div>
        </div>
        <span class="glyphicon glyphicon-ok right" ng-show="register_form.phone.$valid"></span>
    </div>
    <div class="alert alert-danger" ng-show="register_form.phone.$error.phone">
        <strong>请注意!</strong>
        该手机号已注册过,可直接登录。
    </div>
    <div class="alert alert-danger" ng-show="register_form.phone.$touched && !register_form.phone.$error.phone && (register_form.phone.$error.required || register_form.phone.$error.minlength || register_form.phone.$error.maxlength)">
        <strong>请注意!</strong>
        请输入正确的手机号。
    </div>
    <div class="form-group">
        <label for="code">验证码:</label>
        <input type="text" id="code" ng-model="user.code" class="form-control" name="code" required>
        <span class="glyphicon glyphicon-ok right" ng-show="register_form.code.$valid"></span>
    </div>
    <!-- 在表单不合法时禁用提交按钮 -->
    <button class="btn btn-block btn-primary" type="submit" ng-disabled="register_form.$invalid" ng-click="save()">提交</button>
</form>

js:

'use strict';
angular.module('app', [])
.controller('myCtrl', function ($scope) {
  $scope.data = {};
  $scope.save = function () {
    alert('保存成功!')
  }
})
// 判断手机号是否重复
.directive('phone', function ($q, $http) {
  return {
    require: 'ngModel',
    link: function (scope, ele, attrs, ctrl) {
      ctrl.$asyncValidators.phone = function (modelValue, viewValue) {
        var d = $q.defer();
        $http.get('phone.json')
        .success(function (phoneList) {
          if (phoneList.indexOf(parseInt(modelValue)) >= 0) {
            d.reject();
          } else {
            d.resolve();
          }
        });
        return d.promise;
      }
    }
  }
})
// 验证两次输入的密码是否相同的自定义验证
.directive('pwdRepeat', function () {
  return {
    require: 'ngModel',
    link: function (scope, ele, attrs, ctrl) {
      ctrl.$validators.pwdRepeat = function (modelValue) {
        // 当值为空时,通过验证,因为有required
        if (ctrl.$isEmpty(modelValue)) {
          return true;
        }
        return modelValue === scope.data._password "htmlcode">
.form-group {
  position: relative;
}
.right {
  position: absolute;
  right: 10px;
  top: 34px;
  color: green;
}

phone.json:

[
  13758262732,
  15658898520,
  13628389818,
  18976176895,
  13518077986
]

AngularJS自定义表单验证功能实例详解

更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS指令操作技巧总结》、《AngularJS入门与进阶教程》及《AngularJS MVC架构总结》

希望本文所述对大家AngularJS程序设计有所帮助。