Validating your Email with Pure JavaScript
August 21st, 2023 | By Ezekiel Lawson | 7 min read
Email validation is necessary for today's form development, as it prevents your email input from being infiltrated by cyber criminals and keeps malicious data from entering your system. It also helps you properly format and verify the email addresses of users and reject invalid addresses.
Although numerous built-in tools assist with email address validation, it is crucial to understand the fundamental steps and logic underlying email validation. In addition, some of these built-in tools cannot be customized. You will learn the importance of email validation from this article, as well as what Regular expression is, how to use it to validate emails with pure JavaScript, and how to modify your message.
Note: This form of validation is vulnerable if done simply on the front end because malicious users can easily bypass it. Therefore, backend validation serves as a second line of defense against invalid or malicious input.
What is Email Validation?
Let's first discuss what validation is before discussing email validation, since before understanding email validation, you need to grasp what validation is.
So what is Validation in the context of form?
Validation is checking the values inputted by the user in a form. Validation plays a very important role in a web application as it helps keep the input sanitized and safe. Aside from that, it enhances the user experience.
What is Email Validation?
Email validation is a technique for determining whether or not an email address is valid and delivered. It also verifies whether an email address is associated with a trustworthy domain, such as Gmail or Yahoo. Users frequently enter their addresses incorrectly by failing to double-check for formatting or typographical errors.
Email validation is vital because it prevents the transmission of spam and unsolicited emails and improves the quality of your contact database by deleting irrelevant data. It can also be used for fraud prevention measures, particularly on an e-commerce website.
How to validate your Email with Pure JavaScript
Validating your email can be done in different forms as there are built-in tools to help you get started with email validation at a glance. Some of these tools have customized features. While these tools are there, you will learn how to Validate your email with pure Javascript using regular expressions.
Let's study it before incorporating it into your application.
Regular Expression: a pattern of characters that is used for searching and replacing characters in strings. Regular expressions are also known as objects in Javascript. A regular expression might be as simple as a single character or as complex as a pattern.
A regular expression can be implemented in two ways: as a regular expression literal or RegExp() ****constructor function.
Regular expression literal:
const regExp = /edbca/;
The regular expression above consists of a pattern enclosed between slashes.
RegExp() constructor function:
const regExp = new RegExp('edbca');
A sample of the RegExp constructor function is shown in the code above. Keep in mind that there are two approaches to implementing regular expression; this is one of them.
RegExp includes several methods for finding the patterns you require in an email and validating emails. Explore other ways to apply RegExp, which include several methods.
Create form layout
In this section, you will create a basic HTML structure for your form. This form will contain an input field allowing users to enter their email addresses. Add the following code below to your HTML file:
<form id="emailForm">
<label for="email">Enter your email:</label>
<input type="email" name="email" id="email">
<button type="submit">Submit</button>
</form>
Create a JavaScript file and Implement email validation
The final step is to create a Javascript file that will contain the email validation logic.
The first step is to build a Javascript method that retrieves a reference to an HTML element based on its ID attribute. The form element then has an event listener added. The submit event, which is set off when the form is submitted, will be listened to by this. The `validateEmail` function must now be called with warning messages if the user is valid or invalid, and a conditional statement must be used to determine whether the email the user entered is valid:
<script>
const emailForm = document.getElementById("emailForm");
const emailInput = document.getElementById("email");
emailForm.addEventListener("submit", function(event) {
event.preventDefault();
if (validateEmail(emailInput.value)) {
alert("Email is valid!");
} else {
alert("Sorry, this email address is invalid")
}
});
</script>
In the last stage, you'll construct a function called `validateEmail` that accepts an email address as input. After that, you'll create a variable with a regular expression pattern that will be used to validate the users' emails. You must now check the user email result to determine if the pattern is present. You will use the regular expression `test()` function to accomplish that; recall that I stated previously in this post that there are too many methods for regular expression, and this is one of them.
You will determine whether the user-provided email matches the particular pattern in the variable const pattern. The function will return true if it does and false if otherwise:
function validateEmail(email) {
const pattern = /^[A-Za-z\._\-0-9]*\[@\][A-Za-z]*\[\.\][a-z]{2,4}$/
return pattern.test(email)
}
In the above example, you constructed a pattern using the following elements in the regular expression: a series of letters, numbers, underscores, dots, or hyphens followed by @ symbols. then a top-level domain consisting of 2–4 characters follows.
Check out the final result on the page.
Conclusion
Regular expression is an excellent approach for verifying emails; however, you must research the methods and understand which one best fits your email requirements, as there are several to choose from.
In this article, you learned how to validate an email using RegExp in pure JavaScript. This should get you started with email validation using Pure JavaScript.
Jscrambler
The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.
View All ArticlesMust read next
Creating and Validating React Native Forms with Formik
Formik is a useful library for React and React Native that allows keeping track of a form's state, handling submissions, and handling validation.
October 16, 2020 | By Aman Mittal | 11 min read
Stateful vs Stateless vs Pure React Components
React brings forward different types of components, namely class, pure, and function components. How do they differ and when are they the most useful?
January 2, 2020 | By Camilo Reyes | 5 min read