Skip to content

Instantly share code, notes, and snippets.

@nocodesupplyco
Created December 15, 2023 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nocodesupplyco/9085c8d41b3f44cae9c1e2dd30b0848a to your computer and use it in GitHub Desktop.
Save nocodesupplyco/9085c8d41b3f44cae9c1e2dd30b0848a to your computer and use it in GitHub Desktop.
Email Input Validation
// 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