Create a function in JavaScript that checks whether a provided email is valid

This function works by first checking if the email is empty or null. If it is, then the function returns false. Otherwise, the function converts the email to lowercase and then creates a regular expression to match a valid email address. The regular expression checks for the following:

  • The email must contain at least one character before the @ symbol.
  • The email must contain at least one character after the @ symbol.
  • The email must contain a domain name.
  • The domain name must be at least two characters long.

The function then checks if the email matches the regular expression. If it does, then the function returns true. Otherwise, the function returns false.

 
 
function checkMyEmailValid(email) {
  // Check if the email is empty or null.
  if (!email || email === "") {
    return false;
  }
 
  // Convert the email to lowercase.
  email = email.toLowerCase();
 
  // Create a regular expression to match a valid email address.
  const emailRegex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
 
  // Check if the email matches the regular expression.
  const match = emailRegex.test(email);
 
  // Return true if the email is valid, otherwise false.
  return match;
}
 

Here is an example of how to use the checkMyEmailValid() function:

 
 
const email = "john.doe@example.com";
 
const isValidEmail = checkMyEmailValid(email);
 
if (isValidEmail) {
  console.log("The email is valid.");
} else {
  console.log("The email is not valid.");
}