向AngularJS表单添加自定义验证

时间:2015-07-07 17:16:51

标签: javascript jquery angularjs

在下面的表格中,我检查是否需要电子邮件地址:

http://jsfiddle.net/U3pVM/16994/

我想扩展验证,以便检查前两个字符是否以' DD' 。我似乎需要添加一个自定义指令,但我不确定如何将电子邮件字段与指令链接?

小提琴代码:

<form ng-app="myApp" ng-controller="validateCtrl" 
name="myForm" novalidate>

<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
</span>
</p>

<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||  
myForm.email.$dirty && myForm.email.$invalid">
</p>

</form>

var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {

});

app.directive("myValidator", function(){
          // requires an isloated model
          return {
           // restrict to an attribute type.
           restrict: 'A',
          // element must have ng-model attribute.
           require: 'ngModel',
           link: function(scope, ele, attrs, ctrl){

              // add a parser that will process each time the value is
              // parsed into the model when the user updates it.
              ctrl.$parsers.unshift(function(value) {
                if(value){
                  // test and set the validity after update.
                  var valid = value.charAt(0) == 'D' && value.charAt(1) == 'D';
                  ctrl.$setValidity('invalidAiportCode', valid);
                }

                return valid ? value : undefined;
              });

           }
          }
       });

1 个答案:

答案 0 :(得分:0)

以下是我将如何使用身份验证示例:

简单标记:

<input type="email" ng-model="existingUser.email">
<button ng-click="login(existingUser)">Login</button>

控制器:

auth.controller('AuthCtrl', '$scope', 'validation', function($scope, validation) {

  $scope.existingUser = {
    email: '',
    password: ''
  }

  $scope.login = function() {

    validation.validateSignin($scope.existingUser)
      .catch(function(err) {

        // The validation didn't go through,
        // display the error to the user 
        $scope.status.message = err;
      })
      .then(function(res) {

        // Validation passed
        if (res === true) {

          // Do something
        }
    });
  }
}

工厂:

auth.factory('validation', ['$q', function($q) {
  return {
    validateSignin: function(existingUser) {

      var q = $q.defer();

      if (existingUser.email.substring(0,2) !== 'DD') {
        q.reject('The email must start with "DD"');
      }

      q.resolve(true);

      return q.promise;
    }
  }
}]);

让我解释一下发生了什么,首先我要创建一个可以进行验证的工厂。然后我用resolve和reject方法创建一个promise,如果验证失败,将调用reject方法,如果成功,则调用resolve。然后在您的控制器中,您可以根据结果执行操作。

如果有什么不清楚,请告诉我。