i have an email field which is optional but if has value should match the email pattern ?
what about if the form has many optional fields ,like website ,phone ,etc ?
by the way am using FormBuilder, FormGroup, Validators form @angular/forms
i have an email field which is optional but if has value should match the email pattern ?
what about if the form has many optional fields ,like website ,phone ,etc ?
by the way am using FormBuilder, FormGroup, Validators form @angular/forms
Solved this by creating an optionalValidator:
import { ValidatorFn, AbstractControl, Validators } from '@angular/forms';
export function optionalValidator(validators?: (ValidatorFn | null | undefined)[]): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
return control.value ? Validators.compose(validators)(control) : null;
};
}
In my reactive form:
this.form = this._fb.group({
email: [this.contact.email, [optionalValidator([Validators.maxLength(255), Validators.email])]]
});