Search code examples
angularjsformsangular-directive

Password Confirmation Directive


Here is the code I'm using for the 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);

Here is my 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>

However the compareTo directive doesn't work. Looking at the console log I put in the directive, it prints out the string for pass2 and undefined for pass1. Such as aaaa:undefined. This means that they will never be equal and thus there will always be an error. So there must be something wrong with the statement scope.otherModelValue but I can't seem to figure out what is wrong.

Thanks


Solution

  • Try this directive. I haven't tested it, so if it doesn't work, please tell me.

    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));
          });
        }
      };
    });
    

    You can then use the "compare" in the ng-message to output an error.