Custom Validator on reactive form for password and confirm password matching getting undefined parameters into Angular 4

后端 未结 9 1385
遥遥无期
遥遥无期 2020-12-01 00:47

I\'m trying to implement a custom validator to check if the password and password confirm are equal. The problem is that the validator is getting undefined password and conf

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 01:40

    There are two types of validators: FormGroup validator and FormControl validator. To verify two passwords match, you have to add a FormGroup validator. Below is my example:

    Note: this.fb is the injected FormBuilder

    this.newAccountForm = this.fb.group(
      {
        newPassword: ['', [Validators.required, Validators.minLength(6)]],
        repeatNewPassword: ['', [Validators.required, Validators.minLength(6)]],
      }, 
      {validator: this.passwordMatchValidator}
    );
    
    passwordMatchValidator(frm: FormGroup) {
      return frm.controls['newPassword'].value === frm.controls['repeatNewPassword'].value ? null : {'mismatch': true};
    }
    

    and in the templeate:

    Passwords don't match.

    The key point here is to add the FormGroup validator as the second parameter to the group method.

提交回复
热议问题