Validate email address using JavaScript

In order to validate email address using JavaScript, use this simple check:

//where emailString is the string under consideration
if(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{3}$/.test(emailString)) {
 console.log("valid email address");
}

Breakdown of : /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{3}$

  • First part checks for alpha numberic characters, period, underscore and – are allowed.
  • Needs to have an @ sign
  • Last part can only contain 3 characters (a-z or A-Z) alphabets only, if you want anywhere between 2-4 characters, you can use {2,4} instead of {3} like I have.

UPDATE:
This below should work just as well as the above regex. For more useful info, check this out.

(/^[/\w/._-]+@[/\w/.-]+\.[a-zA-Z]{3}$/.test("vikas123@gmail.com"))

The above code in action here

Advertisements

2 thoughts on “Validate email address using JavaScript

  1. Your regular expression fails to validate these two email addresses.

    -hello@yahoo.com (This is invalid, ‘-‘ is not allowed in the beginning of the email address)

    hello@yaho_o.com (This is invalid, underscore is not allowed in domain names)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s