An email, also known as electronic mail, is an electronic message sent via the internet. An email consists of three parts:
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 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 |
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.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.");}}
True
if email matches the pattern, return False
otherwise.validateEmail
function is called to test an email. The function prints a response accordingly.Free Resources