Ahmad Tarawneh
Ahmad Tarawneh

Reputation: 623

How to validate optional field in angular 2?

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

Upvotes: 6

Views: 10852

Answers (2)

Kr Chowdary
Kr Chowdary

Reputation: 29

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

Upvotes: 2

PouleFou
PouleFou

Reputation: 143

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

Upvotes: 11

Related Questions