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
This is a generic code that you can use with every FormGroup:
export function AtLeastOneFieldValidator(group: FormGroup): {[key: string]: any} {
let isAtLeastOne = false;
if (group && group.controls) {
for (const control in group.controls) {
if (group.controls.hasOwnProperty(control) && group.controls[control].valid && group.controls[control].value) {
isAtLeastOne = true;
break;
}
}
}
return isAtLeastOne ? null : { 'required': true };
}
And the usage:
@Component({
selector: 'app-customers',
templateUrl: './customers.component.html',
styleUrls: ['./customers.component.scss']
})
export class CustomersComponent implements OnInit {
public searchCustomerForm: FormGroup;
constructor() { }
ngOnInit() {
this.searchCustomerForm = new FormGroup({
customerID: new FormControl(''),
customerEmail: new FormControl(''),
customerFirstName: new FormControl(''),
customerLastName: new FormControl('')
}, AtLeastOneFieldValidator);
}
}