Developing Web Applications |
Forms require some sort of input. If the user hasn’t entered any information or has entered a bad combination of information, it makes little sense to send the form back to the server. Forms that are submitted without preliminary data validation increase the server’s load (and the user’s frustration) unnecessarily. Validate information as much as possible when the form is submitted.
In fact, don’t stop with the client tier. Just in case the client doesn’t support client-side scripting, validate again as data is passed to the middle tier. Most importantly, use the data integrity and validation rules of your database to protect yourself against inadvertent mistakes in your own business logic. This defensive approach to data validation can save you frustration in the long run; you’ll know that data is protected at all levels of your application.
To validate form input with client-side script, you need to declare an event-handler for the submit event of the form. If your form uses a SUBMIT input type, create an event handler using the name of the form followed by an underscore and the command: “_OnSubmit.” To submit the form, return True from the validation routine. Return False to abort the submission and to return to the form.
If you prefer to use the BUTTON input type on your form, you’ll need to define an event handler using the name of the button followed by an underscore and the command: “_OnClick.” Instead of returning True to submit the form, however, you will need to call the Submit method of the Form object explicitly. This method may not be available on some browsers.
The following client-side script verifies that the form’s user name and e-mail address fields (both required by the form) have been filled in. It then submits the form by returning True from the OnSubmit event-handler:
<SCRIPT LANGUAGE="VBScript">
<!--
Function FeedbackForm_OnSubmit()
'Disallow submit until the form fields have been validated.
FeedbackForm_OnSubmit = False
'Get a reference to the form.
Set theForm = Document.FeedbackForm
'First, check that UserName has been filled in.
If Trim(theForm.UserName.Value) = "" Then
MsgBox "Enter your name.", vbCritical, "Need Input"
theForm.UserName.Focus
Else
'Next, check for the e-mail name.
If Trim(theForm.UserEmail.Value) = "" Then
MsgBox "Enter your e-mail address.", vbCritical, "Need Input"
theForm.UserEmail.Focus
Else
'Continue with submission.
FeedbackForm_OnSubmit = True
End If
End If
End Function
--></SCRIPT>
<form name=FeedbackForm action=TeeFeedback.asp method=POST>
<B>Tell us how to get in touch with you:</B>
<PRE>
Name <INPUT type=TEXT name="UserName"> (Required)
E-mail <INPUT type=TEXT name="UserEmail"> (Required)
Tel <INPUT type=TEXT name="UserTel">
</PRE>
<INPUT type=SUBMIT value="Submit Comments">
<INPUT type=RESET value="Clear Form">
</FORM>