Check if email is valid

A valid email address typically follows this format:

[email protected]

Where:

Here are some common rules to check if an email address is valid:

  1. Local part:
    • Must be at least 1 character long.
    • Can contain letters (a-z, A-Z), numbers (0-9), and special characters (!, #, $, %, ^, &, *, _, -, +, =, ~, `).
    • Can't contain spaces or punctuation marks (except for the @ symbol).
  2. Domain:
    • Must be at least 2 characters long.
    • Can contain letters (a-z, A-Z), numbers (0-9), and special characters (-,.).
    • Can't contain spaces or punctuation marks (except for the . symbol).
  3. TLD:
    • Must be a valid top-level domain (e.g., .com, .org, .net, etc.).
    • Can't contain spaces or punctuation marks.

Using these rules, you can write a simple function to check if an email address is valid:

function isValidEmail(email) {
  const re = /^[a-zA-Z0-9!#$%&*+-/_=~-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
  return re.test(email);
}

This regular expression checks if the email address matches the format described above. If it does, the function returns true, otherwise it returns false.

You can test this function with some examples:

console.log(isValidEmail("[email protected]")); // true
console.log(isValidEmail("example@example")); // false (missing TLD)
console.log(isValidEmail("[email protected]")); // false (invalid domain)
console.log(isValidEmail("[email protected]")); // false (invalid domain)
console.log(isValidEmail("example@example!com")); // false (invalid local part)

Keep in mind that this is a basic validation and may not cover all possible edge cases. For more advanced validation, you may want to use a dedicated email validation library or service.