Here's a bit of Javascript code that is used to make sure that an email address has been entered into a form, before allowing the form to be submitted. If the user leaves the email field blank, a Javascript alert box pops up to remind him/her that the email form field is required.
It doesn't check to see if it is a proper address, it only checks to make sure that SOMETHING has been entered into the email field that is at least 6 characters long. The script to which the form is sent should take care of ensuring that the address is legal, and does not contain any malicious code.
I decided a few years ago to rewrite all of the scripts used on my websites so that they are
To this goal, I revised the script which used to be on this page.
1 function checkEmail()
2 {
3 if (!document.getElementById) return false;
4 var form = document.getElementById("form");
5 var email = document.getElementById("email");
6 var submit = document.getElementById("submit");
7 submit.onclick = function()
8 {
9 if (email.value.length < 6)
10 { alert("You forgot to enter your email address."); return false; }
11 else
12 {
13 var url = "[URL of form-submission script]";
14 form.setAttribute("action",url);
15 form.submit();
16 return true;
17 }
18 return false;
19 }
20 return true;
21 }
Brief explanation:
Line 3 ensures
Lines 4-6 find the three parts of the form that are needed by the script. When the submit button is clicked, line 9 checks the email address. If it does not contain at least 6 characters, a Javascript alert box pops up. Otherwise, the form is submitted in lines 13-15.
Update: To avoid getting Javascript warnings, I recently added some 'return true' and 'return false' statements.
How to use the script:
1) Substitute the address of your form-handling page for the [ ] in line 13. This URL need not appear on your webpage itself, if you want to protect your form from being spammed by robots. Just use a form tag like:
<form id="form" method="post" action="#">
2) Follow the instructions on the main Snippets Page for how to install a javascript function that runs at load time.
3) Make sure that your <form>, <email>, and <submit> tags contain the id's specified in lines 4-6 of the script. If you are following good CSS practices, these tags will already have id's for use by your stylesheet. The script and the stylesheet may use the same identification.
That's it! Now your users won't need to go to the next page to find out that they forgot the required email form field.
There are currently no comments to display.
Click here to add a comment
Rate this page: