The following article describes front-end javascript which prevents a list of supplied email addresses from being used. Because it's only front-end javascript it's not 100% secure. Check out this article if you want to create a safe list of "allowed" email addresses → Plan Signup Rules (a.k.a. restrict signups by email domain).
Here's a script that uses vanilla JavaScript to make the email invalid if the email domain is ends with example1.com
, example2.com
, or example3.com
. You can add, remove, and update these in the code below.
First, we'll need to select the email input element using its data attribute data-ms-member="email"
and add an event listener to the submit button. Then we can define a function that checks if the email domain is one of the invalid domains and sets the input field's validity to false if it is.
Here's the complete code:
<script>
// Select the email input element
const emailInput = document.querySelector('input[data-ms-member="email"]');
// Add event listener to the email input field for change event
emailInput.addEventListener('change', (event) => {
// Check if the email domain is invalid
const email = emailInput.value;
const invalidDomains = ['example1.com', 'example2.com', 'example3.com'];
const emailDomain = email.substring(email.lastIndexOf("@") + 1);
if (invalidDomains.some(domain => emailDomain.endsWith(domain))) {
// Set input field validity to false
emailInput.setCustomValidity("Email domain is not allowed.");
emailInput.reportValidity();
event.preventDefault(); // Prevent form submission
} else {
// Set input field validity to true
emailInput.setCustomValidity("");
}
});
// Add event listener to the form submit button
document.querySelector('form').addEventListener('submit', (event) => {
// Check if the email input field is valid
if (!emailInput.checkValidity()) {
// Display the validation message and prevent form submission
emailInput.reportValidity();
event.preventDefault();
}
});
</script>
Comments
0 comments
Please sign in to leave a comment.