email validator in javascript

Here's a simple function that uses regular expression to validate an email address in JavaScript:

index.tsx
function isValidEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

// Example usage:
const email = "johndoe@example.com";
if (isValidEmail(email)) {
  console.log(`${email} is a valid email address.`);
} else {
  console.log(`${email} is NOT a valid email address.`);
}
321 chars
13 lines

This function uses the regular expression /^[^\s@]+@[^\s@]+\.[^\s@]+$/ to match email addresses that have the correct format. It checks that the email address has at least one non-space character before the '@' symbol, at least one non-space character between the '@' and '.' symbols, and at least one non-space character after the '.' symbol.

The function returns true if the email address matches the regular expression, and false otherwise. You can use this function to validate user input in a web form, for example.

gistlibby LogSnag