Please check this fiddle - https://jsfiddle.net/Ayyappu/1eh28db6/
<body ng-app="app">
<form name="form" ng-submit="form.$valid && vm.login()" novalidate>
<div class="form-group" ng-class="{ 'has-error': form.$submitted && form.password.$invalid }">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" ng-model="vm.password" required pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,15}" />
<div ng-messages="form.$submitted && form.password.$error" class="help-block">
<div ng-message="required">Password is required</div>
<div ng-message="pattern">Invalid format</div>
</div>
</div>
<div class="form-group" ng-class="{ 'has-error': form.$submitted && form.confirmPassword.$invalid }">
<label for="confirmPassword">Confirm Password</label>
<input type="password" name="confirmPassword" class="form-control" ng-model="vm.confirmPassword" required compare-to="vm.password" />
<div ng-messages="form.$submitted && form.confirmPassword.$error" class="help-block">
<div ng-message="required">Confirm Password is required</div>
<div ng-message="compareTo">Passwords don't match</div>
</div>
</div>
<div class="form-group">
<button ng-disabled="vm.loading" class="btn btn-primary">Login</button>
</div>
</form>
</body>
var app = angular.module('app', ['ngMessages']);
app.directive("compareTo", function() {
return {
require: "ngModel",
scope: {
otherModelValue: "=compareTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function(modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
};
});
Validations in the first textbox (Password)
Validations in the second textbox (Confirm Password)
Issue:
Mandatory validation is working fine in both the textboxes. Password policy is also working fine in the first textbox (Password). However, the password match validation in the second textbox (Confirm Password) is working only if the first textbox (Password) passes validation.
e.g., 'Ab1!efgh' is a valid password. If you enter this in both the textboxes, there are no validation errors in the form. However, if you enter just 'a' in the first textbox (Password) and the second textbox (Confirm Password), then there is an error in the second textbox (Confirm Password) saying that the passwords don't match. This clearly shows that 'Confirm password validation is working only if Password field is valid'
I want the password match validation in the second textbox (Confirm Password) to work even if the password you enter in the first textbox (Password) is invalid.
Please help.
By default, vm.password
won't update by ng-model
if the pattern
fails.
you have to use ng-model-options="{allowInvalid: true}"
to allow value change if pattern valid fails.
see this plunker