We often fill out online forms wherein we have to input our email addresses. When we submit it, various fields of the form are validated and tested. Email Validation is also done at that time. In this article, we will learn two methods to do email validation in JavaScript with examples.
What is Email Validation?
Email validation is the process of validating an email. It includes verifying whether an email is correct or not. It ensures that the email address entered by a user follows a specific format and belongs to a valid domain.
When we validate an email, we testify against various conditions and prevent invalid emails from being submitted online. This also reduces the chances of spam emails being provided in forms.
There are various advantages of Validation:
- Enable maintaining a clean and correct database of email addresses.
- Prevents invalid email addresses and bounce rates caused by them.
- Communication is performed with the correct email address.
- Prevents scams and fraud activities.
- Enhances user experience of web forms online by providing them feedback to enter the correct email address.
2 Methods to Do Email Validation in JavaScript
Before we move forward to do it practically, it is vital to understand the anatomy of an email address. An email address consists of two main parts: the Local Part and the Domain Part:
- The local part is the email address portion before the @ symbol. It contains a combination of uppercase letters, lowercase letters, digits, and certain special characters.
- The domain part is the email address portion after the @ symbol. The domain part consists of uppercase letters, lowercase letters, digits, hyphens, and dots. It represents the domain name where the email address is registered.
Now we know all that, let’s now look into various methods to validate an email address in JavaScript:
1) Regular Expression Method
A regular expression is a pattern or a string enclosed between the forward slashes (/) representing rules or conditions for matching the strings. They are primarily used for matching strings to the pattern or regular expression specified.
Hence, as the name suggests, the Regular Expression Method uses a Regular Expression to validate the emails. They define a format or pattern for an email address. If the email matches the regular expression format, it is considered valid otherwise it is considered invalid. The regular expression defined for validating an email consists of rules for both: the Local Part and the Domain Part.
Let us define the regular expression for email validation:
let emailRegularExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
where,
- ^: represents the start of a string
- $: represents the end of a string
- [a-zA-Z0-9.!#$%&’*+/=?^_{|}~-]`: represents the uppercase letter, lowercase letter, digit, or special character allowed in the local part of an email address.
- +: allows one or more occurrences of the preceding character class.
- @: matches the @ symbol.
- [a-zA-Z0-9-]+: represents an uppercase letter, lowercase letter, or digit in the domain part of an email address.
- (?:\.[a-zA-Z0-9-]+)*: allows zero or more occurrences of a dot followed by an uppercase letter, lowercase letter, or digit in the domain part.
Here’s an example of validating an email address with the Regular Expression method with JavaScript:
//declaring a valid email let validEmail="[email protected]"; //declaring am invalid email let invalidEmail="[email protected]"; //defining a regular expression let regex=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; //email validation using the test method, valid returns true, invalid returns false console.log(regex.test(validEmail)); console.log(regex.test(invalidEmail));
Output:
true
false
In this example, we have defined a regular expression to match the email. We have taken a valid email address and an invalid email address. We use the test() method. The test() method returns true for the valid email and returns false for the invalid email. We have got the desired output.
2) Index Values Method
The index values method is another method for email validation. It checks the presence and position of specific characters, such as (@) and (.), in an email address to determine its correctness.
Below are the conditions to be checked with the Index Values Method.
- The (@) symbol and (.) should be present in the email address,
- The index of (@) should be greater than 0.
- The index/position of (.) should be greater than the @ symbol’s position plus one.
- The last (.) character’s position should be less than the length of the email address minus one.
We can use the indexOf() and lastIndexOf() methods in JavaScript to find the positions of the characters. Let us see an example of email validation with the Index Values method:
//function of validating an email function validateEmail(email) { //finding the index of (@) symbol let atIndex=email.indexOf('@'); //finding the index of last (.) character let dotIndex=email.lastIndexOf('.'); //testing condition if (atIndex<1 || dotIndex-atIndex<2) { return false; } else{ return true; } } //declaring a valid email let validEmail="[email protected]"; //declaring am invalid email let invalidEmail="[email protected]"; //validating emails console.log(validateEmail(validEmail)); console.log(validateEmail(invalidEmail));
Output:
true
false
In this example, we have made a function to validate the email by checking the position of the the (@) symbol and the index of last (.) character. We do this using the indexOf() function and the lastIndexOf() respectively. If the function returns true, the email is valid, otherwise the email is not valid. We have obtained the desired result.
Conclusion
In this article, we learned how to do email validation in JavaScript which helps verify the correctness of an email address. We studied the Regular Expression method and the Index Values Method with examples. This is a common question you might get in your assignment, so you might want to get JavaScript homework help from our experts to solve it.