Having trouble incorporating a custom validator formValidator()
on a form group. I am setting the errors to {invalidData: true}
based on a certain condition, and clearing them when the condition is false. However, the issue arises with 'control2' which already has a required validator. Clearing the errors for 'control2' also removes the required validator.
Take a look at the code snippet below:
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;
};
}
Do you have a solution for this issue? Is there something wrong with my custom validator implementation? Your assistance is greatly appreciated.