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.
Validation functions aren't supposed to set errors on controls. They're supposed to return validation error objects.