Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Save Time with Form-Building Routines : Page 4

Build HTML forms in no time with ASP.


Handling Client-Side Data Validation
It is usually a good idea to validate your form using client-side data validation. I prefer to have a single data validation routine that is accessed when the form is submitted. The routine, "ValidateForm", has a single argument—the instance of the form being validated—if valid, it returns true, else it returns false.

This is triggered on the ONSUBMIT event of the form:

<FORM ONSUBMIT="return ValidateForm(this);">

Notice the keyword "return" within the ONSUBMIT event. If you omit that, the validation may not always work properly. Also, the keyword "this" being passed to the function "ValidateForm" signifies that the function will obtain a reference to the actual form. The function does not need to hard code the name of the form within its code.

When the above form is submitted, the browser will look for a JavaScript function "ValidateForm" and execute it:

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
function ValidateForm(f) {
	var retVal;
	retVal = true;
	return retVal;


The function will always return the value of the variable "retVal". Since this is set to "true", the function will always return true.

Let's see how we can incorporate validation for a single text field within our above script code. We'll use the example of the "first_name" field.

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
function ValidateForm(f) {
	var retVal;	
	var msg;
	retVal = true;
	msg = 'There are errors on this form.\nSome required fields 
have not been filled in:\n\n'; if(f.first_name.value=='') { msg += 'Please enter a value for the \'First Name:\' field.\n'; retVal = false; } if(!retVal) { alert(msg + '\n\nPlease correct the errors before continuing.'); } return retVal; } //--> </SCRIPT>

In the above code, we first initialize our error message to generic text to display. Everywhere we wish to have a new line, use the \n statement:

msg = 'There are errors on this form.\nSome required fields have not been
filled in:\n\n';

We then check to see if the first_name field has a blank value. Since we can access the form itself by the argument value 'f', we do not need to know the name of the form:

if(f.first_name.value=='') {

If the value is blank, add a line to the message variable. This allows you to display multiple field errors with a single error message rather than have the user face 10 different pop-up error messages for as many mistakes on the form:

msg += 'Please enter a value for the \'First Name:\' field.\n';

Finally, we set the value of the 'retVal' argument to 'false' to ensure the form is not submitted:

retVal = false;

We can continue to code in the same manner for every control on the form. At the bottom of the script, the code checks to see if we have a problem, and if so, it displays one error message summarizing all error messages accumulated during the code's execution:

if(!retVal) {
		alert(msg + '\n\nPlease correct the errors before continuing.');

We could manually write the code for each one of our controls, but the whole objective of this article is to show you how to do it more efficiently. So we let our trusty "DisplayTextField" routine take care of also writing the Client side JavaScript code. Remember, we can write client side JavaScript very easily with ASP code.

Sub DisplayTextField(byval strLabel, byval strFieldName,  _
	byval strValue, byval intSize, byval intMaxLength, _
	byval blnRequired)
	Response.write "<TD ALIGN=""RIGHT"" VALIGN=""TOP"">" 
	If blnRequired Then
		Response.write "<FONT COLOR=""BLUE"">"
	End if
	Response.Write strLabel & " </FONT></TD>"

	Response.Write "<TD ALIGN=""LEFT"" VALIGN=""TOP"">"

	Response.Write "<INPUT TYPE=""TEXT"" " & _
	" NAME=""" & strFieldName & """ " & _
	" VALUE=""" & strValue & """ " & _
	" SIZE=""" & intSize & """ " & _
	" MAXLENGTH=""" & intMaxLength & """>"
	Response.Write "</TD>"
	' Write the Client Side JavaScript, if required
	If blnRequired Then
		mstrFormValidationScript = mstrFormValidationScript & _
		"if(f." & strFieldName & ".value=='') {" & vbCrLf & _
		"	msg += 'Please enter a value for the \'" & _
			strLabel & "\' field.\n';" & vbCrLf & _
		"	retVal = false;" & vbCrLf & _
		"}" & vbCrLf & vbCrLf 
	End If
End Sub

Notice the new addition at the bottom. If the field is required, we add a bit of JavaScript code to a module level variable (you need to declare this at the top of the page) as "mstrFormValidationScript". The variable "mstrFormValidationScript" will contain the JavaScript required to validate this field. At the end of the routines, the variable "mstrFormValidationScript" will be full of validation logic. To finally dump the contents of this variable, modify the original ASP page code from:

	DisplaySubmitButton  "Submit", "cmd"


	DisplaySubmitButton  "Submit", "cmd"

The new call is to the routine "WriteFormValidationScript" that dumps the form validation code at the bottom of the form.

Sub WriteFormValidationScript()
	Response.Write "<SCRIPT LANGUAGE=""JavaScript"" 
TYPE=""text/javascript"">" & vbCrLf Response.Write "<!--" & vbCrLf Response.Write "function ValidateForm(f) {" & vbCrLf Response.Write " var retVal; " & vbCrLf Response.Write " var msg;" & vbCrLf Response.Write " " & vbCrLf Response.Write " retVal = true;" & vbCrLf Response.Write " msg = 'There are errors on this form.\nSome
required fields have not been filled in:\n\n';" & vbCrLf Response.Write " " & vbCrLf Response.Write mstrFormValidationScript Response.Write " if(!retVal) {" & vbCrLf Response.Write " alert(msg + '\n\nPlease correct the errors
before continuing.');" & vbCrLf Response.Write " }" & vbCrLf Response.Write " return retVal;" & vbCrLf Response.Write "}" & vbCrLf Response.Write "" & vbCrLf Response.Write "//-->" & vbCrLf Response.Write "</SCRIPT>" & vbCrLf End Sub

The WriteFormValidationScript properly formats the Script code to follow at the end of the form. As a result of this, our entire HTML will have the following structure:


In the next column we will take a look at radio buttons as well as list, check, and combo boxes, which are used as lookup tables within data entry forms.

Rama Ramachandran is Vice President of Technology with Imperium Solutions and is a Microsoft Certified Solution Developer and Site Builder. He has extensive experience with building database systems and has co-authored several books including Professional Visual InterDev 6 Programming and Professional Data Access (Wrox). Rama also teaches Visual Basic and Web Development at Fairfield University and University of Connecticut.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date