|
HWG-News Tips Late February 2000Form Validation Tip -- Submitted by Phil JansenHWG-News features member-submitted "tips" in each issue, in the space between articles and announcements. This useful tutorial was too long to run as a tip, but has been provided here as a separate page: Forms validation is a very useful aspect of JavaScript. It can be used to check over a given form and if it finds any problems, such as a blank input box or an invalid e-mail address, it can notify the user and not waste time sending it to a server. Aside from a few modifications to the form tag, its just like any other script. Try out this sample form by leaving an input empty or putting in an e-mail address without an @ sign. Sample only If you forget to enter certain data into the form it will alert you
and cancel the submission. If you do enter all the correct info it will send the
form (not this bogus one though). For future reference, you should know that the
form is named theform, and its two inputs are named email and
user_name. <FORM
NAME="theform"
ACTION="mailto:"
METHOD="POST"
ENCTYPE="multipart/form-data"
onSubmit="return formCheck()">
When the submit button is pressed, the event handler is triggered; it in turn runs function formCheck() which makes sure there are no errors in the form: function formCheck() { if (document.theform.email.value.indexOf("@") == -1 || document.theform.email.value == "") { alert("Please include a proper email address."); return false; } if (document.theform.user_name.value == "") { alert("Please put in a name."); return false; } } First, formCheck() determines if the email input has
an @ sign in it or is empty. If either of these scenarios are true, it alerts
the user and returns false so the form will not be submitted. Then, it
determines if the user_name input is empty. If it is, it also alerts the
user and returns false. Either way, it won't allow the form to be submitted
unless it has been filled out to a reasonable extent. Phil Jansen
Webmaster
More HWG Resources on Javascript
|