6

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

4
  • empty value is not email :) what about the website validation do you have html5 type also :) Commented Jul 23, 2017 at 1:05
  • You are using Reactive Forms, so you can add and remove Validators as needed to a Form Control using setValidators/clearValidators/updateValueandValidity Commented Jul 23, 2017 at 1:05
  • will try these options thank you Commented Jul 23, 2017 at 1:07
  • Some information on those: angular.io/api/forms/AbstractControl Commented Jul 23, 2017 at 1:10

2 Answers 2

11

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])]]
    });
Sign up to request clarification or add additional context in comments.

1 Comment

at Validators.compose(validators)(control) : null for validators showing error type undefined is not assignable to type ValidatorFn | null | undefined
2

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

1 Comment

This regex is far from complete for a good validation. The email: " "_@local is a valid email address but does not pass this test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.