-->

Why Angular 4 FormGroup custom validator not worki

2019-08-26 05:55发布

问题:

Trying to add custom validator formValidator() on a form group. Depending on some condition I am setting the errors {invalidData: true}. But when the condition is false setting errors to null. The control2 itself has required validator. If I set errors to null, it will also clear the required validator.

Refer the below code,

createReactiveForm(data: any) {
    const formGroup = new FormGroup({
        'control1': new FormControl(data.value1),
        'control2': new FormControl(data.value2, [Validators.required])
    }, this.formValidator());
}

formValidator(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
        const control1 = group.controls['control1'];
        const control2 = group.controls['control2'];
        if (control1.value === 'ABC' && control2.value !== 'ABC') {
            control2.setErrors({ invalidData: true });
        } else {
            control2.setErrors(null);
        }
        return;
    };
}

What is the solution for this? Or am I doing anything wrong in the custom validator? Please help.

回答1:

Validation functions aren't supposed to set errors on controls. They're supposed to return validation error objects.

formValidator(): ValidatorFn {
    return (group: FormGroup): ValidationErrors => {
        // use the abstraction provided by the framework
        const control1 = group.get('control1');
        const control2 = group.get('control2');
        // return the correct value depending on your condition
        return control1.value === 'ABC' && control2.value !== 'ABC' ? 
          { invalidData: true } : null;
    };
}