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
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
1 Comment
Maximus Decimus
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.
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" />