2

I am building my own 'Confirm Password' directive in Angular.js. I got my inspiration from this pen.

My directive:

directives.directive('pwCheck', function(){
return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl){
        var pw1 = attrs.pwCheck;
        var pw2 = attrs.ngModel;
        scope.$watchGroup([pw1,pw2],function(value){                                                                                           
            console.log(value);                                                                                                                
            ctrl.$setValidity('pwmatch', value[0] === value[1]);                                                                               
        });                                                                                                                                    
    }                                                                                                                                          
}                                                                                                                                             
});

My form:

<input type="password" class="form-control" name="newpassword" placeholder="Type your new password" ng-model="newpassword" 
ng-pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/"
ng-minlength="8" ng-maxlength="20" ng-required="" />

and:

<input type="password" class="form-control" name="renewpassword" id="renwewpassword" placeholder="Type your new password again"  
ng-model="renewpassword" ng-required="" pw-check="newpassword" />

However, watchGroup does not seem to catch changes (keystrokes) in "newpassword". The console.log() in the directive will print undefined for value[0], while it prints the correct input for value[1].

I can't figure out where the problem is. Any clue?

1 Answer 1

1

I set up a fiddle with your code and it seems to be working fine. But remember, the ng-model of your first input will not be populated unless all of the validation is satisfied:

ng-pattern="/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/" ng-minlength="8" ng-maxlength="20"

If you test with a valid password e.g. ABCDabcd1234, you'll see that both of the values are populated and that keystrokes in both inputs are picked up.

From the Angular Forms guide:

The value of ngModel won't be set unless it passes validation for the input field. For example: inputs of type email must have a value in the form of user@domain.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @sheilak, that was the issue: "the ng-model of your first input will not be populated unless all of the validation is satisfied"!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.