How to Validate Email Address in JavaScript

js-logo

JavaScript is a widely-used programming language today in web development, in both front-end and back-end development, and proper email validation is a must-know skill for every software developer.

When we are developing any website or application in JavaScript, we must create some kind of form from where we are getting the emails from the users. It is very important to validate the input field, before doing something else with that piece of information.

Methods to validate Email in JavaScript

There are many ways to validate email address, the three most popular ways are:

  • Using the regex expression
  • Using HTML in-built email validation
  • Using a third party library

As using regex expression is most popular, we will take a look at how we can validate an email address with a regex expression.

Before We Start Email Validating

Before we start writing the regex expression, we need to know the basics of email validation.

Most of the email addresses are with two parts, the local part and domain part.

The local part of the email address can contain the following:

  • Any letter or number: a-z, A-Z, 0-9.
  • A dot (.) but should not be first or last character.
  • punctuation: “(),:;<>@[]
  • special characters: !#$%&’*+-/=?^_{|}~

The domain part of the email address can contain the following:

  • Any letter or number: a-z, A-Z, 0-9.
  • The hyphen (-) but should not be first or last character.

Email validation using the Regex Expression

There is no general expression to validate an email address. Every developer out there is using a different set of regex in their program to validate an email address. Before we use any regex in our code, we first need to validate it with testing some email addresses, both valid and invalid.

/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

The above example is a regex that can validate almost all (99%) of the email addresses.

Regex Example using JavaScript to Validate Email Adresses

const validateEmail = (email)  => {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email.toLowerCase());
}

In the example above we have a simple JavaScript arrow function, which will validate any email address we insert. The code above is not hard to understand, we are simply using a regular expression to compare it with the email address provided after it is converted to lowercase.

Conclusion

We have converted the most important parts about email validation in JavaScript using the regex expression, As you can see it is not hard at all, although the regex which we use is not easy to understand.




#javascript #validation

Author: Aleksandar Vasilevski |

Loading...