Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, I’m going to show you, how do you check if a string is a valid email in javascript, here I will use regex expression to valid email string.

Which regex we are going to use, it’s a pass bunch of test cases which you can see here.

Let’s start the today’s tutorial title How to check if a string is a valid email in javascript?

Here, we will create a custom function that expects an email string and validate the string using regex, and it will return true and false based valid email string or not.

So, we are going to do

  1. create a validated email function
  2. use functions with the different email addresses
  3. console which email is valid and which is not.
// create validate email function
const validateEmail = (email) => {
  return String(email).toLowerCase().match(/^(([^<>()[\]\\.,;:\[email protected]"]+(\.[^<>()[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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,}))$/);
};


// use function with diffrent email address
// console which email is valid and which not.
if(validateEmail("[email protected]")){
  console.log("[email protected] is a valid email");
} else {
  console.log("[email protected] is a invalid email");
}
 
if(validateEmail("[email protected]")){
  console.log("[email protected] is a valid email");
} else {
  console.log("[email protected] is a invalid email");
}

When running the above program it should which email address is valid and which is not. let’s check the output.

javascript, check if a string is a valid email example
javascript, check if a string is a valid email example

I hope it’s help you, All the best 👍.