In this post we will use Javascript to prevent formsubmission if someone wants to use an email address that belongs to a specific email domain, such as @aol.com or @yahoo.com. If someone tries to submit the form using one of the blacklisted email domains, an alert message will be shown.

First of all we need to create a simple form, here is the HTML (note the “subscription_form” id within the form tag and the “email” id in the input field)

Copy to Clipboard

and here is a little bit of css to make it nice:

Copy to Clipboard

Now we just need to add the necessary Javascript functionality.

First, we need to store some things in variables

Copy to Clipboard

and also to create an array with the blacklisted email domains.

Copy to Clipboard

Then we add an onsubmit event to the form which executes when it is submitted (or when the button is clicked). And within the event we create a few more variables with the “let” keyword.

Here first, we need to get and store the email domain from the entered email address. For this we will create a variable called “emailDomain”. We use the “indexOf()” string method on the email field value to find the domain. And then we use the “substring()” method to slice the domain off the email address and then store it in a variable called “emailVal”.

We declare another variable called “emailFound” and set it to false.

After this we create one more variable called “emailBlacklistLength” which will return the number of elements in the “emailBlacklist” array.

Once we have all these we will loop through the “emailBlacklistLength” to see if there is a match. Inside the for loop we just use a simple if statment to say what to do if there is a match. So if the entered email address has a domain that we have in the blacklist, we set the “emailFound” variable to true and break out of the loop.

Copy to Clipboard

Now, all we have to do is just show the alert message to the user. If the “emailFound” variable is true, we prevent the default behaviour of the form (i.e. we won’t let it to submit) and display the alert message after the for loop.

Copy to Clipboard