How to Validate Email Domains in JavaScript?

Estimated read time 2 min read

To validate email domains in JavaScript, you can use a regular expression to check whether the domain portion of the email address is valid.

Here’s an example of how to validate email domains using a regular expression:

function validateEmailDomain(email) {
  // extract the domain portion of the email address
  const domain = email.substring(email.lastIndexOf("@") + 1);

  // regular expression for validating email domains
  const domainRegex = /^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}$/;

  // test the domain against the regular expression
  return domainRegex.test(domain);

// example usage
const email = "";
if (validateEmailDomain(email)) {
  console.log("Email domain is valid");
} else {
  console.log("Email domain is invalid");

In this code, the validateEmailDomain() function takes an email address as a parameter, and extracts the domain portion of the email using the substring() method and the lastIndexOf() method to find the index of the “@” symbol.

The function then uses a regular expression domainRegex to validate the domain. This regular expression matches domain names consisting of alphanumeric characters, hyphens, and dots, with a minimum length of two characters and a maximum length of five characters.

Finally, the test() method is called on the regular expression object, passing in the domain as a parameter, to check whether the domain is valid or not. The function returns true if the domain is valid, and false otherwise.

You can use this function to validate the domain portion of an email address when a user enters an email in a form or other input field.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply