Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 253
Ahmad Tarawneh Avatar asked Jul 23 '17 00:07

Ahmad Tarawneh


People also ask

What is ValidatorFn in angular?

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 }

How do I add validation in template-driven form?

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.


1 Answers

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])]]
    });
like image 125
PouleFou Avatar answered Oct 05 '22 22:10

PouleFou