The so-called complex form here refers to a form that contains multiple different input types, such as drop-down list boxes, single-line text, multi-line text, numerical values, etc. In situations where such forms often need to be replaced, a dynamic generation program for the form is required. This article introduces just such a system, which uses a database to save form definition data, and uses ASP scripts to dynamically generate form HTML codes and scripts to verify form inputs.
1. Define the database table structure.
You can often see forms such as "Weekly Survey" on the Web. This is a form that needs to be updated frequently. If there is a program that dynamically generates forms and their validation scripts, the workload of making these forms can be greatly reduced.
In the dynamic form generation and validation example in this article, we use an Access database to store the definition information about the form. At the same time, for simplicity, the data entered by the user in the form is also saved to the same database. Defining a form requires two tables: the first table (Definitons) is used to define the form input fields, and the second table (Lists) saves additional information about each input field, such as the selection items of the selection list.
The table Definitons contains the following fields:
FieldName - the variable name assigned to the form input field
Label - text label, the informative text displayed in front of the input field
Type - a single character, which represents the form of the form input field and the type of the input value, as follows:
(t) Text input box, that is, < INPUT TYPE="TEXT" >.
(n) A text input box, but requires a numeric value.
(m) Note content, used for input of comments or other large amounts of text, it is a multi-line text edit box.
(b) Requires input of "yes" or "no". In this implementation, a checkbox will be used to obtain this input, with the text label of the checkbox being "Yes". If the user selects it, the return value is "on".
(r) Radio button.
(l) Drop-down list box.
Min - only valid for numeric input values, the minimum value is given here. In this example there is an "Age" numeric input box with its minimum value set to 1.
Max – The value of this field is relative to the input field form. For numeric input boxes, it represents the maximum allowed value. For example, the Max value of "Age" is 100. For text input boxes, Max represents the maximum number of characters allowed. For multi-line text edit boxes, Max represents the number of text lines in the visible area.
Required - Indicates whether input is required. If a value of this type is not entered, the input validator will report an error. In the form, the values that must be entered are marked with an asterisk, and the user is prompted in the form of a footnote that such values must be entered.
The example form in this article is an ASP programmer questionnaire. The definition of the form in the Definitons table is as follows:
FieldName Label Type Min Max Required
Name Name text (t) - 50 No
Age Age number (n) 1 100 No
Sex Gender single Select button (r) - - Yes
E-mail email address text (t) - - Yes
Language programming language drop-down list box (l) - - No
Lists are used to save some additional information defined in the input field. In this example, "Sex It is used for the two input values " and "Languages". The table Lists is very simple and only contains the following three fields:
FieldName - which form input field the current record belongs to
Value - the value of the selection
Label - the prompt text of the selection that the user sees
The input field "Sex" can only be entered from Two values to choose from: "Male" or "Female". "Language" lists several programming languages that can be applied to the ASP environment, including: VBScript, JavaScript, C, Perl, and "Others."
The third table "Records" saves the content submitted by the user. It also contains three fields. Each record corresponds to a submission by the user:
Record - Remark type, user input saved in the form of a query string.
Created – The date and time the user submitted the form. RemoteIP - The IP address of the form submitter.
In actual applications, it may be necessary to collect more information about users. For simplicity, this example only records two additional information: submission time and user IP address.
2. Preparation
After completing the definition of the above data structure and form, you can then write the script. The script's job is to generate forms and process user-submitted forms.
Whether it is generating or processing a form, the following three processes (tasks) are essential: The first is to determine the validation type. When generating the form, the validation type value is obtained through the query string, and when the form is processed, the hidden fields from the form are obtained. Read. There are four types of form verification methods supported by the program: no verification, client-side JavaScript verification, server-side ASP script verification, and both client-side and server-side verification (codenames are 0 to 3 respectively). If no valid authentication method is specified in the query string, the fourth authentication method defaults. This verification processing method allows us to flexibly apply this form generation and processing system. When the client prohibits the use of JavaScript verification, the verification process can only be performed on the server side. Here is the code to determine the validation type:
Check Validation Type
Here is the quote snippet:
iValType = Request.QueryString("val")
If IsNumeric(iValType) = False Then iValType = 3
If iValType > 3 Or iValType < 0 Then iValType =3
The second task is to open a database connection and create two recordset objects: RS object, which is the main recordset object in this program, used to operate the Definitions table; RSList object, mainly used to read data from the Lists table. The sample program provides two database connection methods: using ODBC DSN or not using ODBC DSN (when using DSN, you need to create a DSN named Dynamic first, and the code for using DSN to connect to the database has been commented out).
The third task is to output some static HTML code before (and after) generating (or processing) the form script, such as <HEAD>< /HEAD>, and releasing the RS, RSList and other objects occupied when the script ends. resource.
In addition to the code that completes the above tasks, there are two types of pages that may be generated by the remaining ASP scripts in the sample application: the question form (see the picture above) and the results page that appears after the form is submitted (the latter is also responsible for recording the results submitted by the user) . The simplest way to determine which part of the script to run is to check whether the form has been submitted: if so, process the form; otherwise, generate the form.
Is it generating a form or processing a form?
The following is a quote snippet:
If Len(Request.Form) = 0 Then
'Generate form... slightly...
Else
'Process the form... slightly...
End If
3. Dynamically generate the form
. When generating the form, the program defines records according to each input field in the Definitons table, and generates the corresponding form HTML code and JavaScript code in turn. The first thing to be generated in the HTML code is the text tag:
Here is the quote snippet:
sHTML = sHTML & vbTab & "< TR >" & vbCrLf & vbTab & vbTab
sHTML = sHTML & "< TD VALIGN=" & Chr(34) & "TOP" & Chr(34)
sHTML = sHTML & " >" & vbCrLf & vbTab & vbTab & vbTab
sHTML = sHTML & "< B >" & RS.Fields("Label")
The program then checks whether the current input field requires input. If necessary, add an asterisk after the label text (indicating that the value must be entered), and for the value that must be entered, the corresponding JavaScript code must be generated to verify it. For radio buttons or select lists, there is a further check that the user actually selected an option; for all other input types, just check that the input value is not empty.
Following the text label are the input elements of the form, and the HTML code for these elements is generated based on the types and attributes specified in the Definitions table. The next step is to generate JavaScript code that performs client-side verification tasks based on the input value requirements. For this example, only numeric values require further checking to ensure that the user's input is indeed a number and that the numeric value is between the allowed maximum and minimum values. After generating the above code, you can end a table row (that is, an input field) and continue processing the next record of the Definitions table. Once all database records have been processed, the next step is to add the HTML code for the "Submit" button and the "Clear" button. If you look at it from another angle, the task of the program here is to generate each input field based on the database record. Each input field occupies a table row, and each table row has two cells: the first cell is used to display text labels, and the second The unit displays the input element itself (see dForm.asp for code).
After the above process is completed, the form's HTML code and validation JavaScript function are saved in the variables sHTML and sJavaScript respectively. Before writing these contents to the page, the program checks whether the client requires JavaScript validation. If such validation is not required, the sJavaScript variable is cleared:
If iValType = 0 Or iValType = 2 Then sJavaScript = ""
After outputting the BODY tag , the program outputs the following JavaScript function:
The following is a quote fragment:
< SCRIPT LANGUAGE="JavaScript" >
< !--
function validate(TheForm){
//Client form validation
< %=sJavaScript% >
return true;
}
function CheckRadio(objRadio){
//Whether a value in the radio button is selected
for(var n = 0; n < objRadio.length; n++){
if(objRadio[n].checked){
return true;
}
}
return false;
}
function CheckList(objList){
//Whether a value has been selected in the selection list
for(var n = 1; n < objList.length; n++){
if(objList.options[n].selected){
return true;
}
}
return false;
}
//-- >
</ /Script >
If the client does not require JavaScript validation, the validate function is left with a "return true" statement. The last two static JavaScript functions (CheckRadio and CheckList) in the above code are used to validate the radio buttons and drop-down list boxes. The validate function will call them when these two input fields need to be validated.
Now you can start writing the form to the page:
< FORM ACTION="./dform.asp" METHOD="POST" NAME="MyForm" onSubmit="return validate(this)" >
Here, only if the validate function returns true Only then perform the form submission operation. Therefore, when the client-side JavaScript verification function is turned off, the validate function will automatically return true.
The next thing to add is a hidden field called val. As mentioned earlier, this value indicates the form's validation mode.
< INPUT TYPE="HIDDEN" NAME="val" VALUE="< %=iValType% >" >
When the user submits the form, the processing script will use this value to determine whether to perform server-side validation.
Then the output is the table mark and table title. The title is saved in the variable sTitleLabel, which value is initialized when the script starts executing:
Here is the quote snippet:
< TABLE BORDER="0" >
<TR>
< TD COLSPAN="2" ALIGN="CENTER" >
< H2 >< %=sTitleLable% >< /H2 >
< /TD >
< /TR >
As an improvement measure, a field FormID can be added to the tables Definitions, Lists and Records. FormID uniquely identifies a form, so that the program can define multiple forms at the same time and save the user response results of multiple forms. As for the sTitleLabel above, we can use another table (such as Forms) to save it.
Following the table mark and table title, the program outputs the HTML form and the code for the "Submit" and "Clear" buttons. After this, the program checks whether the sHTML string contains "*". If it does, it means that there is content that must be entered in the form. At this time, a footnote is output to explain the meaning of the asterisk.
Here is a quote:
< %=sHTML% >
<TR>
< TD COLSPAN="2" ALIGN="CENTER" >
< INPUT TYPE="SUBMIT" VALUE="Submit form" > < INPUT TYPE="reset" VALUE="Clear" >
< /TD >
<%
'Whether there is a form field that requires input, if so, output the form footnote to explain the meaning of '*'
If InStr(sHTML,"*") Then
%>
< /TR >
< TD COLSPAN="2" ALIGN="CENTER" >
< FONT SIZE="2" >Note: Values marked with an asterisk are required. < /FONT>
< /TD >
< /TR >
<%
End If
%>
< /TABLE >
</ /FORM >
So far, the form generation task has been completed.
4. Processing Submission Results
The remaining tasks of the ASP script are server-side form processing, including validation, saving the results to the database, and display of the "Submission Success/Failure" page. A string variable sBadForm is used in this part of the form validation code, and the program uses it to save error information. If sBadForm is empty at the end of the verification process, it means that the form submitted by the user is legal; otherwise, the submission of the form is rejected and sBadForm is returned to the browser.
Regardless of which validation mode your form uses, it's a good practice to check for HTTP_REFERER. This check prevents script theft. To check if a certain POST comes from a page or script from this website, just compare two server variables:
Here is the quote snippet:
If InStr(Request.ServerVariables("HTTP_REFERER"), _
Request.ServerVariables("HTTP_HOST")) = 0 Then
sBadForm = "<LI>The form was submitted from an incorrect location." & vbCrlf
End If
If the hidden field of the form indicates that server-side verification must be performed, the program traverses the form definition database records and performs corresponding checks. The process is very similar to the generation of the form, except that this time the program verifies the form and adds illegal input value information to Just go to sBadForm. See dForm.asp for specific code.
The program finally checks whether sBadForm is empty. If not empty, form submission is rejected and sBadForm is written to the browser. If sBadForm is empty, add a record to the Records table to save the form data. The hidden field val needs to be deleted before saving the form content. This hidden field is always the first input field of the form:
The following is a quote fragment:
If Len(sBadForm) = 0 Then
RS.Open "Records", DB, 3, 2, &H0002
RS.AddNew
RS.Fields("Record") = Mid(Request.Form, InStr(Request.Form, "&") + 1)
RS.Fields("Created") = Now()
RS.Fields("RemoteIP") = Request.ServerVariables("REMOTE_ADDR")
RS.Update
Response.Write("< H1 >Thank you.< /H1 >")
RS.Close
Else
Response.Write("< H1 >Form submission failed. < /H1 >")
Response.Write(vbCrLf & sBadForm)
End If
End If
That's it for server-side form processing. Depending on whether there is a submitted form, we can encapsulate the previous form generation code and the form processing code here with an If statement, so that the two parts of the script share some common code, such as the header of the HTML document, the creation of database objects and the release of resources. wait.
Overall, dForm.asp only has the core functions necessary for dynamic form generation and verification, and ignores the handling of many detailed issues. For example, the multiple form problem mentioned earlier: adding a table to manage multiple forms enables the script to have the ability to manage, generate, and process specified forms. Another glaring lack is the ability to add, delete, and update form-defined data, as well as access to user-submitted result data. Such functionality could be implemented in a stand-alone program, and in most cases could be made into a traditional application. (Applications without B/S structure). Finally, the input field types supported by dForm.asp are also limited. In practice, there may be other form input requirements, such as a dedicated e-mail address input box. However, for websites that frequently update forms, the dynamic form generation and dynamic validation functions discussed in this article are indeed very useful.