Categories
JavaScript Answers

How to validate an email address in JavaScript?

Spread the love

Sometimes, we want to validate an email address in JavaScript.

In this article, we’ll look at how to validate an email address in JavaScript.

How to validate an email address in JavaScript?

To validate an email address in JavaScript, we can use a regex.

For instance, we write

const validateEmail = (email) => {
  const re = /\S+@\S+\.\S+/;
  return re.test(email);
};

console.log(validateEmail("anystring@anystring.anystring"));

to define the validateEmail function that takes the email string.

In it, we define the re regex that matches the segments of the email.

\S+ matches any non space characters.

@ matches @. And “\S+.\S+/` matches the email domain.

Then we call re.test with email to validate that email is an email string.

Conclusion

To validate an email address in JavaScript, we can use a regex.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *