How to Check if a String is a Valid Email in Javascript
In this tutorial, you will learn how to check if a string is a valid email in javascript. Email validation is a very important part of web development because you don’t want to store users in your database with invalid email addresses.
An email consists of 3 parts. The first part can have random text, numbers, or special symbols such as underscores, dots, etc. The second and third part includes @ symbol and a domain name respectively.
We are going to check if string is a valid email using email-validator library. Please copy the code given below, paste it in the javascript file and save it as email.js
In the following example, we will enter a random email in the input field. Upon click of a button, we will check if the string is a valid email or not. Depending upon the result of the check, we will display valid or invalid on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,input
, andbutton
). - The
div
element with a class ofcontainer
is just a wrapper for theinput
andbutton
elements. - The
innerText
for thebutton
element is“Check”
. - By default, the
innerText
for the resultdiv
element is“None”
but we will update it dynamically using javascript. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have included the
email.js
file usingscript
tag which will help us in the email validation process. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div class="container"> <input type="text"> <button>Check</button> </div> <div id="result">None</div> <script src="email.js"></script> <script src="script.js"></script> </body> </html>
.container { text-align: center; margin-bottom: 20px; } #result { text-align: center; border: 1px solid black; height: 15px; width: 225px; color: #fff; margin: auto; padding: 5px; background-color: black; }
Javascript
- We have selected the
button
element,input
element, and resultdiv
element using thedocument.querySelector()
method and stored them in thebtn
,input
, andresult
variables respectively. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are getting the value of the
input
element usingvalue
property and storing it in theemail
variable. - We are calling the
validateEmail()
method and passingemail
variable as a parameter. This method is part of ouremail.js
file. This method will return a Boolean value and we are storing it in theisValid
variable. - We are using
if
statement to execute a certain piece of code depending upon the boolean value. - If the email is valid, we will change the background color of the result
div
element to green and display“Valid”
asinnerText
. - If the email is invalid, we will change the background color of the result
div
element to red and display“Invalid”
asinnerText
.
Email.js
var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/; function validateEmail(email) { if (!email) return false; if(email.length>254) return false; var valid = tester.test(email); if(!valid) return false; // Further checking of some things regex can't handle var parts = email.split("@"); if(parts[0].length>64) return false; var domainParts = parts[1].split("."); if(domainParts.some(function(part) { return part.length>63; })) return false; return true; }
Script.js
let btn = document.querySelector('button'); let input = document.querySelector('input'); let result = document.querySelector('#result'); btn.addEventListener('click', () => { let email = input.value; let isValid = validateEmail(email); if(isValid){ result.style.background = 'green'; result.innerText = 'Valid'; }else { result.style.background = 'red'; result.innerText = 'Invalid'; } })