‘Password’ and ‘Retype password’ fields using AngularJs

The below code snippet shows that how can you implement ‘Password and retype password fields should be matched’ validation/feature using the AngularJs.

The following html code has two password typed input fields:

<body ng-controller="MainCtrl">
    <form name="form1">
      <div>
        <label>Password</label>
        <input type="password" ng-model="user.password" required />
      </div>
        <div>
        <label>Confirm Password</label>
        <input type="password" ng-model="user.confirmPassword" required />
      </div> 
      <span ng-show="form1.$error.passwordMatch">gfgfg</span>
    </form>
  </body>

We are using $watchGroup which is a variant of $watch() where it watches the values of the ‘password’ and ‘retype password’ input fields. If the user enters into any field, then validate() method will be called.

var app = angular.module('plunker', []);
 
app.controller('MainCtrl', function($scope) {
  $scope.user = {
    password: '',
    confirmPassword: '',
    userId: ''
  }
  $scope.$watchGroup(['user.confirmPassword','user.password'], function() {
    validate();
  });
  var validate = function() {
    // values
    var val1 = $scope.user.password;
    var val2 = $scope.user.confirmPassword;
 
    // set validity
    $scope.form1.$setValidity('passwordMatch', !val1 || !val2 ||  val1 === val2);
  };
});

Each time when validate() method will be called, the validity state of the form ‘form1’ will be changed.

Author: Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.