密码确认指令

Password Confirmation 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 肯定有问题,但我似乎无法弄清楚问题是什么。

谢谢

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

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"输出错误。

要创建自己的检查尝试指令 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>