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

后端 未结 9 1354
遥遥无期
遥遥无期 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:13

    I would do the same as Shailesh Ladumor but adding the following line before returning in the validation function:

    c.get('confirm_password').setErrors({'noMatch': true});
    

    So that the validation function looks like this:

    passwordConfirming(c: AbstractControl): { invalid: boolean } {
        if (c.get('password').value !== c.get('confirm_password').value) {
            c.get('confirm_password').setErrors({'noMatch': true});
            return {invalid: true};
        }
    }
    

    This will not only set the hole userForm as an invalid form group, but it will also set confirm_password as an invalid form control.

    With this you can later call the following function in your template:

    public getPasswordConfirmationErrorMessage() {
    if (this.userForm.get('confirm_password').hasError('required')) {
      return 'You must retype your password';
    } else if (this.userForm.get('confirm_password').hasError('noMatch')) {
      return 'Passwords do not match';
    } else {
      return '';
    }
    

    }

提交回复
热议问题