简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM