如何在AngularJS中检查密码和确认密码相同

时间:2015-09-17 09:50:04

标签: javascript angularjs

任何人都可以帮助我验证AngularJS中的密码和确认密码字段

1 个答案:

答案 0 :(得分:0)

有很多方法可以实现这个目标。一种方法是使用指令

<input type="password" name="confirmPassword" 
    ng-model="registration.user.confirmPassword"
    required 
    compare-to="registration.user.password" />

<div ng-messages="registrationForm.confirmPassword.$error"
  ng-messages-include="messages.html"></div>

//指令

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

        ngModel.$validators.compareTo = function(modelValue) {
            return modelValue == scope.otherModelValue;
        };

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

module.directive("compareTo", compareTo);

Reference