密码确认指令

时间:2016-01-09 14:55:57

标签: angularjs forms angular-directive

以下是我用于指令的代码:

var compareTo = function() {
return {
  require: "ngModel",
  scope: {
    otherModelValue: "=compareTo"
  },
  link: function(scope, element, attributes, ngModel) {

    ngModel.$validators.compareTo = function(modelValue) {
        console.log(modelValue + ":" + scope.otherModelValue);
      return modelValue == scope.otherModelValue;
    };

    scope.$watch("otherModelValue", function() {
      ngModel.$validate();
    });
  }
  };
};
app.directive("compareTo", compareTo);

这是我的HTML:

       <div class="form-group">
            <label>Password</label>
            <span>Must contain at least eight characters, including uppercase, lowercase letters and numbers</span>
            <input type="password" 
                class="form-control"
                name="password"
                ng-model="signUpPass1"
                ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/"
                required>
            <div ng-messages="signUpForm.password.$error" class="formMsgContainer">
                <span class="formMsg" ng-message="pattern">Passwords Does Not Meet the Criterias!</span>
            </div>
        </div>
        <div class="form-group">
            <label>Confirm Password</label>
            <input type="password"
            class="form-control"
            name="conPass"
            ng-model="signUpPass2"
            compare-to="signUpPass1"
            required>
            <div ng-messages="signUpForm.conPass.$error" class="formMsgContainer">
                <span class="formMsg" ng-message="compareTo">Passwords Do Not Match!</span>
            </div>
        </div>

然而compareTo指令不起作用。查看我在指令中输入的控制台日志,它打印出pass2的字符串和pass1的undefined。例如aaaa:undefined。这意味着它们将永远不会相等,因此总会出现错误。所以陈述scope.otherModelValue一定有问题,但我似乎无法弄清楚出了什么问题。

由于

2 个答案:

答案 0 :(得分:0)

尝试此指令。我没有测试过,所以如果它不起作用,请告诉我。

app.directive("compareTo", function() {
  return {
    require: "ngModel",
    link: function(scope, element, attributes, controller) {
      scope.$watch(attributes.ngModel, function(value) {
        controller.$setValidity('compare', (element.val() === value));
      });
    }
  };
});

然后,您可以使用ng-message中的“compare”输出错误。

答案 1 :(得分:0)

要创建自己的检查,请尝试指令use-form-error。它易于使用,可为您节省大量时间。

实例jsfiddle

 <form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
   <label>Confirm password</label>
  <input ng-model="confirmPassword" required />
  <div use-form-error="isSame" use-error-expression="password && confirmPassword && password!=confirmPassword" ng-show="ExampleForm.$error.isSame">Passwords Do Not Match!</div>
</form>