4

Is there a way to make a form invalid if two inputs don't match (like passwords), in Angular? Similar to form.password.$error.required?

2 Answers 2

5
 pwd1:<input type="password" ng-model="pwd1" required /><br />
 pwd2:<input type="password" ng-model="pwd" required /><br />

      <div ng-show="pwd1 && pwd">Invalid:
        <span ng-show="pwd1!==pwd">Wrong</span>
        <span ng-show="pwd1===pwd">Correct</span>
      </div>

This just checks if both the passwords are same. Angular Form validation

Also check this Angular Ui which has password match directive

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

1 Comment

I saw many solutions with ng-directive but this is simpler. I wonder if there any flaw on this because til now it works fine for me.
3

You can use Angular UI, it has a ui-validate directive:

<input name="password" required ng-model="password">
<input name="confirm_password" ui-validate=" '$value==password' " ui-validate-watch=" 'password' ">

Or, you can build your own directive for that

myApp.directive('matchPassword', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        scope: {
            matchPassword: '='
        },
        link: function (scope, elem, attrs, ctrl) {
            scope.$watch(function () {
                return (ctrl.$pristine && angular.isUndefined(ctrl.$modelValue)) || scope.matchSenha === ctrl.$modelValue;
            }, function (currentValue) {
                ctrl.$setValidity('matchPassword', currentValue);
            });
        }
    };
});

and use it like so:

<input required name="passwordConfirm" match-password="model.Password" />

Comments

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.