email.validator.ts 731 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
import { ValidationErrors, AbstractControl } from '@angular/forms';

// tslint:disable-next-line:max-line-length
const RE: RegExp = new RegExp(
  "^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"
);

/**
 * Validates an email address using the same regular expression the server uses.
 *
 * @param email the form control to validate
 */
export function emailValidator(email: AbstractControl): ValidationErrors {
  const value = email.value;
  if (!value) {
    return null;
  }
  return RE.test(email.value)
    ? null
    : {
        email: true,
        validateEmail: {
          valid: false
        }
      };
}