Angular 4 reactive forms retype password on signup (group validation)

Angular 4 was released recently and as a result there aren’t many community answers for this version. I was working on the sign up page for my latest project and I took a few wrong turns when designing the “retype password” field in a reactive form.

Screen Shot 2017-05-29 at 10.25.37 AM.png

My original thought process was to attach a control validator onto the second password field which would access the parent. Here is an example of this validator:

  static equalTo(equalControlName): ValidatorFn {

      return (control: AbstractControl): {
          [key: string]: any
      } => {
          if (!control['_parent']) return null;

          if (!control['_parent'].controls[equalControlName])
              throw new TypeError('Form Control ' + equalControlName + ' does not exists.');

          var controlMatch = control['_parent'].controls[equalControlName];

          return controlMatch.value == control.value ? null : {
              'equalTo': true
          };
      };
  }
  }

This solution might work for Angular 2 but for Angular 4 there is a much simpler method with the only downside being it doesn’t work with Form Builder as far as I know.

The second and third args for the Form Group initializer are for group level validators. These can validate multiple controls on a single form and are perfect for this password confirmation.

const form = new FormGroup({
  password: new FormControl('', Validators.minLength(2)),
  passwordConfirm: new FormControl('', Validators.minLength(2)),
}, passwordMatchValidator);

function passwordMatchValidator(g: FormGroup) {
   return g.get('password').value === g.get('passwordConfirm').value
      ? null : {'mismatch': true};
}

This passwordMatchValidator simply takes a FormGroup (you don’t have to care about this because it is handled by Angular) and returns a validator response when the values of the controls form the passed FormGroup are equal.

Hope this helps!

 
337
Kudos
 
337
Kudos

Now read this

Angular 4 + Bootstrap masonry type grid layout

Quick post here on how to make these masonry layouts in Angular 4 with Bootstrap: Originally I looked into Javascript frameworks such as Masonry, but I couldn’t get it to work with Angular 4. There is actually a much simpler approach to... Continue →