简体   繁体   中英

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?

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]);

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;
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM