Creating a registration form earlier today and realized angular did not come packaged with password confirm directives for ngMessages. So I needed to create one.
First things first, attach your new directive into your module.
// Creating a new directive
(function ()
{
'use strict';
angular
.module('app.register')
.directive("compareTo", compareTo);
})();Within your function you will now need to define your compareTo function to handle your password and password confirm comparison.
// Logic for new compareTo directive
function compareTo()
{
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();
});
}
};
}Now in the html we can use the new compareTo directive inside the input and pass the data into your function to compare passwords.
<!-- Initial Password Input -->
<md-input-container class="md-block" md-no-float>
<input type="password" name="password" ng-model="vm.password" placeholder="Password" required>
<div ng-messages="registerForm.password.$error" role="alert">
<div ng-message="required">
<span>Password field is required</span>
</div>
</div>
</md-input-container>Lastly within ngMessages, we can confirm the password using the compare-to directive, and check the validation of the compareTo with ng-message="compareTo". Input will now not allow mismatch passwords and either show an error or accept the input and submit their data.
<md-input-container class="md-block" md-no-float>
<input type="password" name="passwordConfirm" ng-model="vm.passwordConfirm"
compare-to="vm.password"
placeholder="Password (Confirm)"
required>
<div ng-messages="registerForm.passwordConfirm.$error" role="alert">
<div ng-message="required">
<span>Password (Confirm) field is required</span>
</div>
<div ng-message="compareTo">
<span>Passwords must match</span>
</div>
</div>
</md-input-container>