check if email is valid in javascript

You can check whether an email address is valid or not in JavaScript by using Regular Expressions. Here's a code snippet that demonstrates how to do this:

index.tsx
function validateEmail(email) {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(String(email).toLowerCase());
}

// example usage 
const email = "example@example.com";
if (validateEmail(email)) {
  console.log("Email is valid");
} else {
  console.log("Email is not valid");
}
289 chars
13 lines

In this code, we define a function validateEmail that takes an email address as its argument. The regular expression used in this function ensures that the email address is in the format username@domain.tld. If the email address matches this format, the function returns true. Otherwise, it returns false. Finally, we call this function with an example email address and log the output to the console.

gistlibby LogSnag