0

So I have a reactive form with validators. I created custom validator to check if password matches with confirm password. Here's what it looks like:

this.form = this.formBuilder.group({
        'emailAddress': new FormControl(null, [
            Validators.required,
            Validators.email,
            this.checkEmailAddress.bind(this)
        ]),
        'username': new FormControl(null, [
            Validators.required,
            Validators.maxLength(16),
            this.checkUsername.bind(this)
        ]),
        'passGroup': this.formBuilder.group({
            'password': new FormControl(null, [
                Validators.required
            ]),
            'confirmPassword': new FormControl(null, [
                Validators.required
            ])
        }, {
                validator: checkPassword
            })
    });

Here's my custom function:

function checkPassword(group: FormGroup): { [s: string]: boolean } {
    if (group.value.password !== group.value.confirmPassword) {
        return { 'passwordMismatch': true };
    }
    return null;
}

After a little bit of googling, I found out that I should not use the word function. However, this is the confusing part.

If I re-save (without any actual change), the compiler will recompile and it will be successful.

If I remove the word function, the compiler will also be successful BUT the validator of my form will be broken.

I have also tried
validator: this.checkPassword and validator: this.checkPassword.bind(this) AFTER removing the function word but it gives me lot of errors.

Jonathan Lightbringer
  • 435
  • 2
  • 12
  • 27

1 Answers1

1

based in Angular2 validator which relies on multiple form fields You can put in the component.ts the validators function and referred as this.functionName

    this.form = this.formBuilder.group({
       ...,
      'passGroup': this.formBuilder.group({
        'password': new FormControl(null, [
          Validators.required
        ]),
        'confirmPassword': new FormControl(null, [
          Validators.required
        ])
      }, {
          validator: this.checkPassword('password', 'confirmPassword')
        })
    });

checkPassword(passwordKey: string, confirmPasswordKey: string) {
    return (group: FormGroup): { [key: string]: any }| null => {
      let password = group.get(passwordKey);
      let confirmPassword = group.get(confirmPasswordKey);
      if (password.value == confirmPassword.value)
        return null;
      return {
        mismatchedPasswords: true
      };
    }
  }
Eliseo
  • 50,109
  • 4
  • 29
  • 67