Angular: Validators.email is invalid if empty

I am creating an application in Angular (4.0) that contains form ( FormGroup). In this form, I have an email input (s FormControl) and I use Validators.emailto validate.

import { Validators } from '@angular/forms';

// ...
let validators = [];
if ([condition]) {
    validators.push(Validators.email);
}
let fc = new FormControl([value] || '', validators);
// ...

But when the input is empty, it is invalid (it has a class ng-invalid), even if it is not required.

Is this the right behavior? What can I do?

+13
source share
5 answers
However solution

eric2783 is pretty good - if the result of work Validators.emailchanges in the future , then this custom validator will become incompatible with the output signal of angular.

, :

private customEmailValidator(control: AbstractControl): ValidationErrors {
  if (!control.value) {
    return null;
  }

  return Validators.email(control);
}
+12

, , :

<input type="email" name="email" [(ngModel)]="model.Email" [email]="model.Email!='' && model.Email!=null">
+11

, :

<input [(ngModel)]="model.email"  [email]="model.email!==''">

(, ).

+5

, , . , , :

private customEmailValidator(control: AbstractControl): {[key: string]: any} {
    const emailError = Validators.email(control);
    if (control.value && emailError) {
        return {'email': {}};
    }

    return null;
}

validators.push(Validators.email); validators.push(this.customEmailValidator);

angular , , .

+4

:

<input [(ngModel)]="model.email" [email]="!!model.email">
+2

Source: https://habr.com/ru/post/1017180/


All Articles