Confirm Password Validation in AngularJS

Monday, October 13, 2014

AngularJSForm validation and custom validation directives are relatively easy with the changes in Angular 1.3. Try the sample plunk here.

Let’s look at the scenario where we need to confirm a new user’s password during registration. Registration is not so common in this day and age of federated identity, but is still a useful example and a frequent requirement.

Custom compareTo directive in AngularJS

A Custom Directive

We could put logic into a model to confirm a password, but it is probably better to separate the logic into a reusable directive. AngularJS already provides directives for the standard HTML validation attributes like required. All we need to do is follow a similar pattern.

1. Require the ngModel controller.

2. Add a method to the ngModel controller’s $validators object. Angular will invoke the function when the model value changes. The function returns a boolean, and a return value of false will set the corresponding ngModel’s $error property automatically.

The compare-to directive looks like the following:

var 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();
            });
        }
    };
};

module.directive("compareTo", compareTo);

You can use the directive inside of markup like so:

<input type="password" name="confirmPassword"  
        ng-model="registration.user.confirmPassword" 
        required 
        compare-to="registration.user.password" />
            
<div ng-messages="registrationForm.confirmPassword.$error" 
      ng-messages-include="messages.html"></div>

The ng-messages directives, also new in 1.3, makes it easy to provide common error messages for form inputs. You can also see them at work in the plunk.


Comments
gravatar Quinntyne Brown Tuesday, October 14, 2014
Much needed improvement! Thanks for the post. I was just fighting with this in Angular 1.2...
gravatar Houssem Saturday, October 25, 2014
look's interesting ... thanks ..
gravatar Jan Aagaard Friday, November 14, 2014
I had to replace return modelValue == scope.otherModelValue; with return modelValue === scope.otherModelValue.$modelValue; I am not sure if I should use $modelValue or $viewValue. I also replaced == with === because I believe that strict comparison should be used when possible, but not completely sure that strict comparison is possible here in all cases.
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!