Save Time with Form-Building Routines

Save Time with Form-Building Routines

SP programmers frequently develop Web apps that rely on displaying data within forms linked to a back-end database. To do this, you either create forms displaying data contained within a database, or display a form whose data you plan to place within a database when the form is submitted. In this column I’ll share some useful form-building routines that will take some of the grunt work out of developing and maintaining those HTML forms.

Common Form-Building Tasks
When developing forms in ASP pages, there are usually a few tasks that get repeated for each control placed on the form. These include:

  • Defining the control on the form
  • Providing it a valid name tied to the back-end database
  • Figuring out its appearance as well as maximum allowed data for entry
  • Writing client-side JavaScript for data entry validation

If you are using a visual editor such as FrontPage, Visual InterDev, Dreamweaver, or HomeSite to build your HTML form, you can drag and drop controls to create a form. However, these tools will not automatically generate the code needed to handle all the aspects above. You need to set the properties for each control individually to define its appearance, maximum data allowed, data validation, etc. There is a coding alternative to the above approach, especially suited for ASP programmers who do not use a visual tool.

A Textbox Field Example
Let’s take a typical data entry form as an example. It may contain one or more text boxes to hold data that ends up within the database table. For example, suppose we have a text box to accept the user’s first name that is actually linked to the field “first_name” within the database table. To build this, use the following HTML code:

This would create a very simple, inelegant text box depending on your browser. The right way to do it is to specify its size, maximum length, and initial value if any. To make sure all text boxes appear neatly on your data entry screen, use the SIZE attribute. In addition, use the MAXLENGTH attribute to ensure the amount of data entered in the text box is not more than the size of the field in the database table. And finally, if the record in the database already contained a value for this field, you would pre-fill it in the text box using the VALUE attribute:

First Name: 

We can now continue to put other controls underneath the first one to build our data entry screen. However, as we put double controls (label+textbox) underneath each other like this, their placement on screen will be out of order depending on the size of each label. It is better if they are placed in one row, within two columns of a two-column table, the label in the left column and the text box in the right column. Assuming we have created a table begin tag, the new code would be:

   First Name:   	

This would provide us with a label and a text box in two neat columns. If we want 10 such controls, we would need to repeat the same code 10 times. This is where form-building code routines come in handy.

The Form Routines

Figure 1. Sample HTML Form: Create a Forms routine that requires three separate SELECT tags.

Instead of writing all the HTML code by hand, use the convenient Form routines. Suppose we plan to build the form in Figure 1.

As you can see, it is a standard data entry form that accepts contact information. Most of the fields are pre-filled, possibly from a database, where the user has entered the data before, or the system already contains the information. This is also a very simple data entry form utilizing only text boxes.

Let’s take this one step at a time. Suppose we just want to display the first nine controls?the contact information text boxes. This would be the code:

	WriteFormBegin 	“frmInfo”, “pgApply.asp”, _					“POST”, “return ValidateForm(this);”	WriteTableBegin 600		DisplayTextField 	“First Name:”, “first_name”, _						objRS(“first_name”), 60, 35, True	DisplayTextField 	“Last Name:”, “last_name”, _						objRS(“last_name”), 60, 35, True	DisplayTextField 	“Title:”, “title”, _						objRS(“title”), 60, 80, False	DisplayTextField 	“Company:”, “company”, _						objRS(“company”), 60, 80, True	DisplayTextField 	“Address:”, “address_1”, _						objRS(“address_1”), 60, 80, True								DisplayTextField 	“”, “address_2”, _						objRS(“address_2”), 60, 80, False	DisplayTextField 	“City:”, “city”, _						objRS(“city”), 40, 35, True	DisplayTextField 	“State:”, “state”, _						objRS(“state”), 40, 2, True	DisplayTextField 	“Zip:”, “zipcode”, _						objRS(“zipcode”), 40, 10, True	DisplaySubmitButton  “Submit”, “cmd”		WriteTableEnd		WriteFormEnd

That’s it. The above 14 lines of ASP code actually end up generating more than 100 lines of HTML code. As you can see, we call the “DisplayTextField” routine to automatically obtain a Label + Textbox combination. Let’s see what each piece does.

The Code Explained
The first piece of code we call is the routine WriteFormBegin. This takes a few arguments and creates the HTML FORM tag:

And this is the routine that produced it:

Sub WriteFormBegin(byval strFormName, byval strFormAction, _byval strFormMethod, byval strFormSubmit)	Response.Write “
“” Then Response.Write ” NAME=””” & strFormName & _””” ID=””” & strFormName & “””” End if Response.Write ” ACTION=””” & strFormAction & “””” Response.Write ” METHOD=””” & strFormMethod & “””” If strFormSubmit “” Then Response.Write ” ONSUBMIT=””” & strFormSubmit & “””” End if Response.Write “>”End Sub

The routine creates the form begin tag based on the arguments sent to it. Two of the arguments are really optional, however, in VBScript, since there is no optional argument type, we check to see if the first and the last arguments are blank. If they are, no action is taken, otherwise, the HTML acquires a NAME (and ID) and an ONSUBMIT attribute. Notice that all values are enclosed within double quotes. To make sure you have a double quote (“) character within an ASP string, you use double double quotes (“”) to indicate a literal double quote.

Note: I am writing this code on a Windows 2000 IIS server. In that scenario, the ASP Response.Buffer property is true by default. Hence the multiple Response.write statements do not pose performance degradation. Because Response buffering is true, all the response.writes are batched together and sent to the browser as one. If you are using ASP under Windows NT, you might want to set the Response.Buffer to true at the top of the page.

The last call we make is to close the form and it is very simple: WriteFormEnd. All it does is write out the “” tag.

Sub WriteFormEnd()	Response.write ““End Sub

The next two calls create and end an HTML table:

Sub WriteTableBegin(byval intTableSize)	Response.Write “ “” Then		Response.Write ” WIDTH=””” & intTableSize & “”””	End if	Response.Write “>”End SubSub WriteTableEnd()	Response.Write “
“End Sub

The DisplayTextField Routine
We now come to the heart of this column, the DisplayTextField routine. This is the actual routine that displays a label and a text box combination in two columns of a table. It accepts six arguments:

strLabelThe text for the label to use
strFieldNameThe name of the text box
strValueThe value inside the text box
intSizeThe size of the text box
intMaxLengthThe maximum length of the data allowed inside the text box
blnRequiredFlag to indicate this is a required field

In our example code above, we are using the contents of a recordset object (“objRS”) to populate the values of the text box.

This is the code within the DisplayTextField routine:

Sub DisplayTextField(byval strLabel, byval strFieldName,  _	byval strValue, byval intSize, byval intMaxLength, _	byval blnRequired)	Response.Write “”	Response.write “” 	If blnRequired Then		Response.write “”	End if	Response.Write strLabel & “?”	Response.Write “”	Response.Write “”		Response.Write “”	Response.Write “”	End Sub

The DisplayTextField outputs a label and a text box using this HTML text:

First Name:

In this case, I used the design in which a required field’s label is indicated in blue, while an optional field’s label will be displayed in black (the default). You can modify this by using a scheme where a required field will be in red or bold, or use an additional IMAGE (an asterisk or a blurb) next to the label or text box.

By using the above routine, the job of displaying 10 separate labels and text boxes with different values, options, sizes, and appearances has been reduced to 10 lines of ASP code in the calling program. If you place these routines within a common “include” file, you can reuse this code over and over again in several different pages.

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:

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:

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.

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

msg = ‘There are errors on this form.
Some required fields have not been
filled in:


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.

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 + ‘

Please 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 “” 	If blnRequired Then		Response.write “”	End if	Response.Write strLabel & “?”	Response.Write “”	Response.Write “”		Response.Write “”		‘ 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.
‘;” & 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”		WriteTableEnd		WriteFormEnd	


	DisplaySubmitButton  “Submit”, “cmd”		WriteTableEnd		WriteFormEnd		WriteFormValidationScript

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

Sub WriteFormValidationScript()	Response.Write “” & vbCrLfEnd 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.


Share the Post: