Email address validation is one of the most important features in a user registration form. You should validate the user’s email address in case the user tries to register a different email address or in case the email address is invalid.
There are many ways to validate an email address in JavaScript. In this blog post, we will compare some different methods and see which one is the best. So, let’s get started!
CONTENTS
Why Email validation is important?
The user registration form is the first step in your web application. It’s very important that the user provide correct information, including the email address. You can send a confirmation email to the user. This is a common practice.
How to validate an email address in Javascript?
Email validation should not be relied upon entirely through JavaScript. Because JavaScript can be easily disabled. So email validation should be done on the server-side as well as client-side. Let’s see how we can validate email through JavaScript.
HTML:
<label for="email">Enter an email address: </label>
<input id="email" />
<button id="btn">Validate Email</button>
Here we have taken one textbox and one command button. After entering an email address, when a user clicks on Validate Email button, an alert box will be opened depending on the email address.
JavaScript:
const emailValidate = (email_address) => {
return email_address.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
document.getElementById("btn").addEventListener("click", function(){
const email = document.getElementById("email").value;
if (emailValidate(email)) {
alert(email + ' is valid email address.');
}else{
alert(email + ' is invalid email address.');
}
});
Validate email using HTML5
If your browser supports HTML5, you can easily validate email without JavaScript. Use the below code:
<form>
<input type="email" placeholder="youremail@example.com" required>
<input type="submit">
</form>
Conclusion:
Email addresses are easy to steal, and when you don’t validate them, they can lead to spam, security holes, or worse. So always try to validate email on both client and server-side.