I'm building an Angular 5 form. I have a requirement for contact information on my form (email or phone). Either an email address OR a phone number is required, but not both. How would I create a custom validator for this scenario? From the docs it seems that validators are responsible for just one control, whereas my validator would need to be aware of multiple controls to check all their values.
ngOnInit() {
this.form = this.formBuilder.group({
'name': [null, [Validators.required]],
'email': [null, []], // A user can provide email OR phone, but
'phone': [null, []], // both are not required. How would you do this?
});
}
One possible solution is declaring a function that takes as an argument the form itself, for example:
export function emailAndPhone() {
return (form: FormGroup): {[key: string]: any} => {
return (form.value.phone && form.value.email) ||
(!form.value.phone && !form.value.email)
? { emailAndPhoneError : true }
: null;
};
}
Set the validator function to your form definition using the validator extras:
ngOnInit() {
this.form = this.formBuilder.group({
'name': [null, [Validators.required]],
'email': [null, []], // A user can provide email OR phone, but
'phone': [null, []], // both are not required. How would you do this?
}, { validator: emailAndPhone() });
}
If you need to recognize when the validation has detected an invalid input just make sure that emailAndPhoneError that was defined earlier is present on the form error list. Like this
*ngIf="myForm.hasError('emailAndPhoneError')" //true means invalid
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With