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
ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null. interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null }
To add validation to a template-driven form, you add the same validation attributes as you would with native HTML form validation. Angular uses directives to match these attributes with validator functions in the framework.
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])]]
});
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