TypeScript Function Validates an Email Address

Posted 05/03/2019 3:26 PM by Corey Klass

Validating email addresses on the client side in Angular can be done using a regular expression (though complicated as it may be). Below you can find a TypeScript function that will validate the input as an email address.

// validates an email address
static emailValidate(textToValidate: string): boolean {
  const email = textToValidate.toLowerCase();
  const regex = /(?:[a-z0-9!#\u0024%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#\u0024%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;

  const emailIndex = email.search(regex);

  const validFlag = (emailIndex === 0);

  return validFlag;
}