I need to have a validation on a form in order to make the user fill at least one of two fields
I've tried with a custom validator like this:
export function conditionalValidator(
predicate: () => boolean,
validator: ValidatorFn
): ValidatorFn {
return formControl => {
if (!formControl.parent) {
return null;
}
let error = null;
if (predicate()) {
error = validator(formControl);
}
return error;
};
}
and then in my form
this.myForm= this.fb.group({
field1: ['', conditionalValidator(() => !(this.myForm.get('field1').value || this.myForm.get('field2').value), Validators.required)],
field2: ['', conditionalValidator(() => !(this.myForm.get('field1').value || this.myForm.get('field2').value), Validators.required)],
});
this.myForm.get('field1').valueChanges.subscribe(_ => {
this.myForm.updateValueAndValidity();
});
this.myForm.get('field2').valueChanges.subscribe(_ => {
this.myForm.updateValueAndValidity();
});
but I don't know why it doesn't work
I also tried with a more "handcraft" way (stackblitz link here) but with no luck either