5
votes

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

2
empty value is not email :) what about the website validation do you have html5 type also :)Ahmad Tarawneh
You are using Reactive Forms, so you can add and remove Validators as needed to a Form Control using setValidators/clearValidators/updateValueandValidityR. Richards
will try these options thank youAhmad Tarawneh
Some information on those: angular.io/api/forms/AbstractControlR. Richards

2 Answers

10
votes

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])]]
    });
2
votes

ex:

contactForm:FormGroup = new FormGroup({});

ngOnInit() {
const validateEmail = "[a-zA-Z0-9._\-]+[@]+[a-zA-Z0-9\-]+[.]+[a-zA-Z]{2,6}";
this.contactForm.addControl("email", new FormControl('', Validators.pattern(validateEmail));
}

this way you can create optional fields but when you have data that need to be validated

Edit: Added - to allowed characters