Angular: Validators.email invalid if empty

angular, forms, javascript, validation

Solution

eric2783's solution is pretty good, however - if, in future, the output of `Validators.email` will change, then this custom validator will become not compatible with the angular's validator output.

Here's what you should do to keep the compatibility:

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

  return Validators.email(control);
}

Problem

I'm creating an app in Angular (4.0), that contains a form (`FormGroup`). In this form I have an email input (with `FormControl`), and I use `Validators.email` for validation. ``` 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 an `ng-invalid` class), even if it's not required. Is this a proper behavior? What can I do?

Original source