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
- create a validated email function
- use functions with the different email addresses
- console which email is valid and which is not.
// create validate email function
const validateEmail = (email) => {
return String(email).toLowerCase().match(/^(([^<>()[\]\\.,;:\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,}))$/);
};
// use function with diffrent email address
// console which email is valid and which not.
if(validateEmail("infinitbility@gmail.com")){
console.log("infinitbility@gmail.com is a valid email");
} else {
console.log("infinitbility@gmail.com is a invalid email");
}
if(validateEmail("infinitbility@gmailtest")){
console.log("iinfinitbility@gmailtest is a valid email");
} else {
console.log("infinitbility@gmailtest 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.
I hope it’s help you, All the best 👍.