Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading