Skip to content
-
JavaScript Application For Email Validation
Last Updated :
23 Jul, 2025
The Email Validation Project in JavaScript aims to create an efficient system for verifying the authenticity and format of email addresses. This tool ensures data accuracy, reduces errors, and enhances the user experience by preventing invalid email submissions.
Project Preview
Email validation Application in JavaScriptWhat Will You Learn?
We’ll build an application that allows users to
- Enter an email address in an input field.
- Validate the entered email against a regular expression.
- Display an error message if the email format is invalid.
- Provide visual feedback when the email is valid or invalid.
The application will include a clean user interface and provide instant feedback to the user.
Email validation App - HTML and CSS
This HTML code creates a simple email validation form. It allows users to enter their email address. This CSS code provides styling for the email validation form, ensuring a clean and modern look.
HTML
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 400px;
}
h2 {
text-align: center;
margin-bottom: 20px;
}
form {
display: flex;
flex-direction: column;
}
label {
margin-bottom: 8px;
font-size: 16px;
}
input[type="text"] {
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
button {
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.error-message {
color: red;
font-size: 14px;
display: none;
margin-bottom: 15px;
}
</style>
</head>
<body>
<div class="container">
<h2>Email Validation Form</h2>
<form id="emailForm">
<label for="email">Enter your email:</label>
<input type="text" id="email" name="email" placeholder="example@domain.com" required>
<span id="error-message" class="error-message"></span>
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
In this code
- The container centers the form and applies styling for a clean and modern design.
- The input field allows users to enter their email address, with a placeholder for guidance.
- The error-message span displays validation errors dynamically.
- The submit button triggers the validation logic.
- CSS provides styles for responsiveness, error highlighting, and hover effects.
Email validation App - JavaScript Logic
This JavaScript code handles email validation for the form submission. It checks if the entered email matches a specified pattern and displays an error message if the format is incorrect.
JavaScript
document.getElementById("emailForm").addEventListener("submit", function (event) {
event.preventDefault();
const email = document.getElementById("email").value;
const errMsg = document.getElementById("error-message");
const pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (pattern.test(email)) {
errMsg.style.display = "none";
alert("Email is valid! Form Submitted.");
document.getElementById("emailForm").reset();
} else {
errMsg.style.display = "block";
errMsg.textContent = "Please enter a valid email address.";
}
});
In this code
- The form is selected using its ID, and an event listener is added to handle submissions.
- The emailPattern regular expression checks the validity of the entered email address.
- If the email is valid, an alert confirms the submission, and the form resets.
- If invalid, an error message is displayed dynamically below the input field.
Complete Code
HTML
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 400px;
}
h2 {
text-align: center;
margin-bottom: 20px;
}
form {
display: flex;
flex-direction: column;
}
label {
margin-bottom: 8px;
font-size: 16px;
}
input[type="text"] {
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
button {
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
.error-message {
color: red;
font-size: 14px;
display: none;
margin-bottom: 15px;
}
</style>
</head>
<body>
<div class="container">
<h2>Email Validation Form</h2>
<form id="emailForm">
<label for="email">Enter your email:</label>
<input type="text" id="email" name="email" placeholder="example@domain.com" required>
<span id="error-message" class="error-message"></span>
<button type="submit">Submit</button>
</form>
</div>
<script>
document.getElementById("emailForm").addEventListener("submit", function (event) {
event.preventDefault();
const email = document.getElementById("email").value;
const errMsg = document.getElementById("error-message");
const pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (pattern.test(email)) {
errMsg.style.display = "none";
alert("Email is valid! Form Submitted.");
document.getElementById("emailForm").reset();
} else {
errMsg.style.display = "block";
errMsg.textContent = "Please enter a valid email address.";
}
});
</script>
</body>
</html>
Similar Reads
JavaScript Form Validation JavaScript form validation checks user input before submitting the form to ensure it's correct. It helps catch errors and improves the user experience.What we are going to CreateIn this article, we will guide you through creating a form validation application. This application will validate essentia
10 min read
JavaScript - How to Validate Form Using Regular Expression? To validate a form in JavaScript, you can use Regular Expressions (RegExp) to ensure that user input follows the correct format. In this article, we'll explore how to validate common form fields such as email, phone number, and password using RegExp patterns.1. Validating an Email AddressOne of the
4 min read
Form validation using the jbvalidator Plugin jbvalidator is a jQuery and Bootstrap based plugin which supports both client and server form validations. The provided HTML data attributes are easy to use and understand. The plugin gives multi-language facilities along with custom validation rules and messages.The plugin can be used by downloadin
4 min read
How to create form validation by using only HTML ? In Web Development, we often use JavaScript with HTML to validate the form, but we can also do the same via HTML in the following ways. HTML <input> required Attribute HTML <input> type Attribute HTML <input> pattern Attribute HTML <input> required Attribute: In input tag of
2 min read
How to create form validation by using only HTML ? In Web Development, we often use JavaScript with HTML to validate the form, but we can also do the same via HTML in the following ways. HTML <input> required Attribute HTML <input> type Attribute HTML <input> pattern Attribute HTML <input> required Attribute: In input tag of
2 min read
How to create form validation by using only HTML ? In Web Development, we often use JavaScript with HTML to validate the form, but we can also do the same via HTML in the following ways. HTML <input> required Attribute HTML <input> type Attribute HTML <input> pattern Attribute HTML <input> required Attribute: In input tag of
2 min read
`;
$(commentSectionTemplate).insertBefore(".article--recommended");
}
loadComments();
});
});
function loadComments() {
if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) {
if (!isfollowingApiCall) {
isfollowingApiCall = true;
setTimeout(function(){
if (loginData && loginData.isLoggedIn) {
if (loginData.userName !== $('#followAuthor').val()) {
is_following();
} else {
$('.profileCard-profile-picture').css('background-color', '#E7E7E7');
}
} else {
$('.follow-btn').removeClass('hideIt');
}
}, 3000);
}
}
});
}
$(".accordion-header").click(function() {
var arrowIcon = $(this).find('.bottom-arrow-icon');
arrowIcon.toggleClass('rotate180');
});
});
window.isReportArticle = false;
function report_article(){
if (!loginData || !loginData.isLoggedIn) {
const loginModalButton = $('.login-modal-btn')
if (loginModalButton.length) {
loginModalButton.click();
}
return;
}
if(!window.isReportArticle){
//to add loader
$('.report-loader').addClass('spinner');
jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', {
PRACTICE_API_URL: practiceAPIURL,
PRACTICE_URL:practiceURL
},function(responseTxt, statusTxt, xhr){
if(statusTxt == "error"){
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
});
}else{
window.scrollTo({ top: 0, behavior: 'smooth' });
$("#report_modal_content").show();
}
}
function closeShareModal() {
const shareOption = document.querySelector('[data-gfg-action="share-article"]');
shareOption.classList.remove("hover_share_menu");
let shareModal = document.querySelector(".hover__share-modal-container");
shareModal && shareModal.remove();
}
function openShareModal() {
closeShareModal(); // Remove existing modal if any
let shareModal = document.querySelector(".three_dot_dropdown_share");
shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" }));
document.querySelector(".hover__share-modal-container").append(
Object.assign(document.createElement('div'), { className: "share__modal" }),
);
document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" }));
const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"];
socialOptions.forEach((socialOption) => {
const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" });
const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` });
const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` });
const shareLink = (socialOption === "Copy Link") ?
Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) :
Object.assign(document.createElement('a'), { className: "link-container" });
if (socialOption === "LinkedIn") {
shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`);
shareLink.setAttribute('target', '_blank');
}
if (socialOption === "WhatsApp") {
shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
if (socialOption === "Twitter") {
shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`);
shareLink.setAttribute('target', "_blank");
}
shareLink.append(icon, socialText);
socialContainer.append(shareLink);
document.querySelector(".share__modal").appendChild(socialContainer);
//adding copy url functionality
if(socialOption === "Copy Link") {
shareLink.addEventListener("click", function() {
var tempInput = document.createElement("input");
tempInput.value = window.location.href;
document.body.appendChild(tempInput);
tempInput.select();
tempInput.setSelectionRange(0, 99999); // For mobile devices
document.execCommand('copy');
document.body.removeChild(tempInput);
this.querySelector(".share__option-text").textContent = "Copied"
})
}
});
// document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));
}
function toggleLikeElementVisibility(selector, show) {
document.querySelector(`.${selector}`).style.display = show ? "block" : "none";
}
function closeKebabMenu(){
document.getElementById("myDropdown").classList.toggle("show");
}