Search code examples
javascriptangularvalidationcustomvalidator

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

  • You should use validators not validator:

    this.form = new FormGroup({
     // fields
    }, { validators: this.matchingPasswords });
    

    Perhaps it's also better to move that matchingPasswords to an exported utility function, but that's just personal code preference.

    Other working notations are:

    this.form = new FormGroup({
     // fields
    }, this.matchingPasswords);
    
    this.form = new FormGroup({
     // fields
    }, [this.matchingPasswords]);