'Problems with the custom validator in Angular

I know that the question in question has already been asked in many other posts but in all the proposed solutions I cannot find one that solves the problem for me.

I'm trying to create a validator to check that the entered confirmation password is the same as the password.

This is my build form code:

    this.form = new FormGroup({
      name: new FormControl('', [Validators.required]),
      surname : new FormControl('', [Validators.required]),
      username: new FormControl('', [Validators.required, Validators.email]),
      tempUsername: new FormControl('', [Validators.required, Validators.email]),
      password: new FormControl('', [Validators.required, Validators.minLength(8), Validators.maxLength(16)]),
      passwordTemp: new FormControl('', [Validators.required]),
    }, { validator: this.matchingPasswords }
    );
  }

and this is my validator method:

  public matchingPasswords(c: AbstractControl): ValidationErrors | null {
    const password = c.get(['passwords']);
    const confirmPassword = c.get(['passwordTemp']);

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

in line 8 of the build form I get the following error:

TS2345: Argument of type '{ validator: (c: AbstractControl) => ValidationErrors; }' is not assignable to parameter of type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'.   Object literal may only specify known properties, and 'validator' does not exist in type 'ValidatorFn | ValidatorFn[] | AbstractControlOptions'.

Any ideas?



Solution 1:[1]

Use validators instead of validator

{ validators: this.matchingPasswords }

and this

public matchingPasswords: ValidatorFn = (c: AbstractControl): ValidationErrors | null => {
        const password = c.get('passwords');
        const confirmPassword = c.get('passwordTemp');

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

        return null;
    };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zainhassan