I have a form that needs to check if one of a group of checkboxes is checked if a dropdown has a specific value. I have a validator that works on the checkboxes, but I only need it to check if the dropdown is a specific value. Below is the form and validation code. I've tried having the validator bind like this.requireCheckboxesValidator.bind(this), but then it just seems to ignore the validator
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;
};
}
I can suggest a different approach.
You can subscribe to valueChanges of your dropdown field and then if the specific value that is selected is what you expect, you can use addValidator to add the certain validator to your checkboxes form control.
I also like your idea of adding a custom validator (definitely the better approach) and it should actually work in that way as well. From what I understand you're trying to add the validator for the checkboxes only if the dropdown has a specific value ? In that case you need to change your logic to something like:
Object.keys(formGroup.controls).forEach(key => {
const control = formGroup.controls[key];
if (control.value === true) {
checked++;
}
let dropdownValue = undefined;
if (key === 'dropdownFormControlKey') {
dropdownValue = control.value;
}
});
if (checked < 1) { // --- Add check to also see if the dropdown's value is what you expect and only then return the error
return {
requireCheckboxesToBeChecked: true,
};
}
return null;
};