Created
December 15, 2023 21:43
-
-
Save nocodesupplyco/9085c8d41b3f44cae9c1e2dd30b0848a to your computer and use it in GitHub Desktop.
Email Input Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Validate email field for only business emails | |
document.addEventListener("DOMContentLoaded", function () { | |
// UPDATE THIS - ID on the <form> | |
let form = document.getElementById("pardot-form"); | |
// UPDATE THIS - ID on text element to display errors | |
let errorElement = document.getElementById("email-domain-error"); | |
form.addEventListener("submit", function (event) { | |
// UPDATE THIS - ID on the email <input> | |
let emailInput = document.getElementById("email"); | |
let emailValue = emailInput.value.trim().toLowerCase(); | |
// Regular expression to validate email format | |
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; | |
if (!emailRegex.test(emailValue)) { | |
errorElement.textContent = "Please enter a valid email"; | |
errorElement.style.display = "block"; | |
event.preventDefault(); // Prevent the form from submitting | |
} else { | |
// Check if the email contains any of the restricted domains | |
let restrictedDomains = ["yahoo.com", "outlook.com", "hotmail.com", "gmail.com"]; | |
let isInvalidDomain = restrictedDomains.some(function (domain) { | |
return emailValue.endsWith("@" + domain); | |
}); | |
if (isInvalidDomain) { | |
errorElement.textContent = "Please provide a business email address."; | |
errorElement.style.display = "block"; | |
event.preventDefault(); // Prevent the form from submitting | |
} else { | |
// Clear the error message if the email is valid | |
errorElement.textContent = ""; | |
errorElement.style.display = "none"; | |
} | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment