Regular Expressions – validating the Email

How to validate an email address with following rules using regular expressions?

  • There should one @ sign in the email address.
  • The email should start with a letter and can include letters and numbers and underscore symbol  _ . This constitutes the left hand side of the email from the @ sign.
  •  Right hand side of the @ sign should be the domain name. This should include the period . and left hand side of the period should be alpha numeric and right hand side should be letters.
  • Lower case and upper case is supported.

Lets get started on how to validate for above rules using regular expressions.

/^

This means the reg expression has started.

/^[a-zA-Z]{1}

This part means the first letter should be a letter. Either lower case a-z or upper case A-Z.

/^[a-zA-Z]{1}[a-zA-Z0-9]_

After that We check for alpha numeric characters and underscore character.

/^[a-zA-Z]{1}[a-zA-Z0-9]_@

Then we check for the @ sign.

/^[a-zA-Z]{1}[a-zA-Z0-9]_@[a-zA-Z0-9]\-

Then we check for the domain name alpha numeric characters and – dash sign.

/^[a-zA-Z]{1}[a-zA-Z0-9]_@[a-zA-Z0-9]\-\.

Then we check for the period in the domain name.

/^[a-zA-Z]{1}[a-zA-Z0-9]_@[a-zA-Z0-9]\-\.[a-zA-Z]

Then we check for the domain extension letters.

/^[a-zA-Z]{1}[a-zA-Z0-9]_@[a-zA-Z0-9]\-\.[a-zA-Z]$/

Last part is to mark the end of the reg expression.

Hope this help you understand regular expressions a bit more. I have added the regular expression for javascript. But this will be similar for other languages as well. Please share how to validate email in other languages using regex below in the comments.

Resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Advertisements