I am facing an issue with my form validation logic. I have a set of checkboxes that need to be validated only when a specific value is selected from a dropdown. The current validator checks the checkboxes regardless of the dropdown value. Here's the code snippet for my form and validation function:
readonly closeFormGroup: FormGroup;
constructor(
formBuilder: FormBuilder,
) {
this.closeFormGroup = formBuilder.group({
notes: [null],
reason: [1, Validators.required],
checkBoxGroup: new FormGroup({
checkBox1: new FormControl(false),
checkBox2: new FormControl(false),
checkBox3: new FormControl(false),
checkBox4: new FormControl(false),
checkBox5: new FormControl(false),
} ,this.requireCheckboxesValidator())
});
}
public requireCheckboxesValidator(): ValidatorFn {
return function validate(formGroup: FormGroup) {
let checked = 0;
console.log(formGroup);
Object.keys(formGroup.controls).forEach(key => {
const control = formGroup.controls[key];
if (control.value === true) {
checked++;
}
});
if (checked < 1) {
return {
requireCheckboxesToBeChecked: true,
};
}
return null;
};
}