|
Using JavaScript to Make Form Fields Mandatory
One of the problems we Webmasters face when constructing forms is getting our users to fill in all the required fields. We can augment the form with all kinds of notes that warn the user of the dire consequences that can result from leaving a field blank, but users have a way of ignoring these things. A better approach is to use a little JavaScript know-how to make one or more form fields mandatory. That is, make it so the browser won't submit the form unless the user puts something in those fields. For example, there isn't any way for my MailForm script to be able to reliably detect the user's e-mail address, which means you have to rely on your readers to enter their e-mail address so that you can contact them. One thing you could do is use JavaScript to make your form's e-mail field mandatory. Here are the steps to follow to set this up:
Step 1: Update the <FORM> Tag
<FORM
ACTION="javascript:alert('Thank you for entering an e-mail address!')"
METHOD="POST"
NAME="MyForm"
onSubmit="return validate(MyForm)">
Note that my ACTION attribute just displays a JavaScript alert box. In your form, you'll use a legitimate script URL.
Step 2: Set Up the Rest of Your Form <B>Please enter your e-mail address:</B><BR> <INPUT TYPE=TEXT SIZE=35 NAME="Email">
Step 3: Add the JavaScript Here's a JavaScript that does this:
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate(frm) {
//
// Check the Email field to see if any characters were entered
//
if (frm.Email.value.length == 0)
{
alert("Tsk tsk. Please enter an e-mail address.")
frm.Email.focus()
return false
}
}
//-->
</SCRIPT>
What's happening here is that the validate procedure checks the length of whatever value the user
entered into the specified field (Email, in this case). If the value is 0, it means the user didn't
enter a value. So the script displays an alert, sets the "focus" back to the Email field, and then returns false, which tells the browser not to submit the form.
Notice two things here:
Here's a sample form so you can try this out for yourself:
This works fine, but the user may just enter a token character to fool the script. To take things up a notch, you can have the script check the entered value to see if it contains an "@" symbol. Here's a JavaScript that does this:
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate2(frm)
{
//
// Check the Email field to see if any characters were entered
//
if (frm.Email.value.length == 0)
{
alert("Tsk tsk. Please enter an e-mail address.");
frm.Email.focus();
return false;
}
//
// Now check the Email field for the "@" symbol
//
if (frm.Email.value.indexOf("@") == -1)
{
alert("Caught you! Please enter a valid e-mail address.");
frm.Email.focus();
return false;
}
}
//-->
</SCRIPT>
Try it out:
Copyright © 1995-2008 Paul McFedries and Logophilia Limited |