Angular2 validator which relies on multiple form fields

To kind of reiterate on the methods other have posted, this is the way I’ve been creating FormGroup validators that don’t involve multiple groups.

For this example, simply provide the key names of the password and confirmPassword fields.

// Example use of FormBuilder, FormGroups, and FormControls
this.registrationForm = fb.group({
  dob: ['', Validators.required],
  email: ['', Validators.compose([Validators.required,  emailValidator])],
  password: ['', Validators.required],
  confirmPassword: ['', Validators.required],
  firstName: ['', Validators.required],
  lastName: ['', Validators.required]
}, {validator: matchingPasswords('password', 'confirmPassword')})

In order for Validators to take parameters, they need to return a function with either a FormGroup or FormControl as a parameter. In this case, I’m validating a FormGroup.

function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
  return (group: FormGroup): {[key: string]: any} => {
    let password = group.controls[passwordKey];
    let confirmPassword = group.controls[confirmPasswordKey];

    if (password.value !== confirmPassword.value) {
      return {
        mismatchedPasswords: true
      };
    }
  }
}

Technically, I could have validated any two values if I knew their keys, but I prefer to name my Validators the same as the error they will return. The function could be modified to take a third parameter that represents the key name of the error returned.

Updated Dec 6, 2016 (v2.2.4)

Full Example: https://embed.plnkr.co/ukwCXm/

Leave a Comment