How to validate an email address in JavaScript
An email, also known as electronic mail, is an electronic message sent via the internet. An email consists of three parts:
- Username
- The @ sign
- Domain Name
The domain name can be further divided into two parts, i.e., the string before dot (.) is called the hostname, and the string after it is called the top-level domain, which is a part of website’s address that tells the type of website. For example, in the email address above, “educative” is the hostname, and “io” is the top-level domain.
Email validation
Email validation is the process of checking the structure of an email address. The validity of an email address refers to the proper syntax and structure.
The correct structure should be like a username followed by @ sign, then there should be a hostname, followed by dot and the top-level domain.
All the emails that do not follow the pattern above are considered invalid. Here are some examples of valid and invalid email addresses:
Valid Email Addresses | Invalid Email Addresses |
answers@educative.io | answers@educative |
test_123@gmail.com | test 123@gmail.com |
contact@microsoft.com | contactmicrosoft.com |
student@mit.edu | student@mitedu |
admission@ox.ac.uk | admission@@ox.ac.uk |
Using the regular expression
A regular expression, also called regex, is a sequence of characters representing a specific search pattern. Regex is commonly used in computer programming and text processing to search for and match strings based on particular rules or patterns defined by the regex.
Regular expression to check email validity is:
/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/
Let’s understand how this regular expression works:
^matches the start of the string.[^\s@]+matches one or more characters that are not whitespace or the @ symbol.@matches the @ symbol.[^\s@]+matches one or more characters that are not whitespace or the @ symbol.\.matches a period character.[a-zA-Z]{2,}matches two or more alphabetic characters (this matches the top-level domain).$matches the end of the string.
Coding example
function validateEmail(email) {// regular expression for email validationconst pattern = /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/;// return true if the email matches the pattern, false otherwise.return pattern.test(email);}// Emails to testconst emails = ["answers@educative.io", "answers@educative"];for (let i = 0; i < emails.length; i++) {if (validateEmail(emails[i])) {console.log("The email \"" + emails[i] + "\" is a valid email address.");} else {console.log("The email \"" + emails[i]+ "\" is an invalid email address.");}}
Code explanation
- Line 3: The pattern of regular expression is defined.
- Line 6: An input email is tested over defined pattern. It will return
Trueif email matches the pattern, returnFalseotherwise. - Line 10: A sample email is taken for test.
- Lines 12–17: The
validateEmailfunction is called to test an email. The function prints a response accordingly.
Free Resources