I have a form where I\'m collecting phone numbers (mobile, personal, other). I need to have at least input populated. I\'m trying to use Angular2 FormBuilder.
Afte
I use an atLeastOne function that creates a custom validator based on any existing validator:
import { FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms';
export const atLeastOne = (validator: ValidatorFn) => (
group: FormGroup,
): ValidationErrors | null => {
const hasAtLeastOne =
group &&
group.controls &&
Object.keys(group.controls).some(k => !validator(group.controls[k]));
return hasAtLeastOne ? null : { atLeastOne: true };
};
The beauty is that you can use any validator with it and not just Validators.required.
In OP's case, it'll be used like this:
{
phone: this._fb.group({
other: [''],
personal: [''],
mobile: [''],
}, { validator: atLeastOne(Validators.required) })
}