jonsamwell/angular-auto-validate

Validate Password Match

Closed this issue · 4 comments

How do you validate two input fields to ensure they match e.g. when you have a password input and a password confirm?

You can create a directive to handle this:

(function() {
    'use strict';

    angular.module('app.register').directive('equalsTo', equalsTo);

    function equalsTo() {
        return {
            restrict : 'A',
            require : 'ngModel',
            scope : {
                otherModelValue : '=equalsTo'
            },
            link : function(scope, element, attributes, ngModel) {

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

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

})();
<div class="form-group">
    <label class="control-label">Password</label> <input type="password" ng-model="vm.password" class="form-control" required>
</div>
<div class="form-group">
    <label class="control-label">Confirm password</label> <input type="password" ng-model="vm.password2" equals-to="vm.password" class="form-control" required>
</div>

@jgesser Thanks for this
@JaydroidBot I've created a plunker for this which also shows how to add a custom error message for this new validator

http://plnkr.co/edit/W1NFc8tRueMEzJrpOUeZ?p=preview

@jpmckearin I don't remember taking code from there, but it is really very similar. I'm sorry any way, I should pay more attention.