Dynamic generation and verification of complex forms

Source: Internet
Author: User
Tags dsn servervariables

A complex form contains multiple input types, such as drop-down list box, single-line text, multi-line text, and numeric values. When you often need to replace such forms, you need a dynamic form generation program. This article describes a system that stores form definition data in a database, dynamically generates form HTML code using ASP scripts, and verifies the form input script.
1. Define the database table structure

Forms such as weekly surveys are often seen on the Web. This is a form that needs to be updated frequently. If there is a program that dynamically generates the form and its verification script, it can greatly reduce the workload of making these forms.

In the dynamic form generation and verification examples in this article, we use an Access database to store the definition information about the form, the data entered by the user in the form is also saved to the same database. Two tables are required to define a form: the first table (definitons) is used to define the input fields of the form, and the second table (lists) Stores additional information about each input field, such as selecting items in the list.

Table definitons contains the following fields:

Fieldname -- assign the variable name of the form input field
Label -- text label, indicating the text displayed before 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) text input box, but enter a number value.
(M) Remarks content, used for comments or input of a large number of texts. It is a multi-line text editing box.
(B) enter "yes" or "no ". In this implementation, check boxes are used to obtain such input. The text label of the check box is "yes ". If you select it, the return value is "on ".
(R) Single-choice 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" (AGE) number input box, and its minimum value is set to 1.
Max -- the value of this field is related to the input field format. For the number input box, it indicates the maximum allowed value. For example, the max value of "Age" is 100. For text input boxes, Max indicates the maximum number of characters allowed. In the multi-line text editing box, Max indicates the number of lines of text in the visible area.
Required -- indicates whether the input is required. If this type of value is not input, the input validators report an error. In the form, the value that must be entered is marked with a star number, and the user is prompted in the form of a footer that this type of value must be entered.
The example form in this article is an ASP programmer questionnaire. The definition of this form in the definitons table is as follows:

Fieldname label type min max required
Name text (t)-50 no
Age age (n) 1 100 No
Sex sex radio button (R)--Yes
E-mail address text (t)---Yes
Language Programming Language drop-down list box (l)--No

The lists table is used to save some additional information about the input domain definition. In this example, there are two input values: "sex" and "Ages. The lists table is very simple and contains only the following three fields:

Fieldname -- form input field of the current record
Value -- Value of the selected item
Label -- displays the prompt Text of the selected item.
The input field "sex" can only be selected from two values: "male" or "female ". "Language" lists several programming languages that can be used in ASP environments, including VBScript, JavaScript, C, Perl, and "others ".

The third table "records" stores the content submitted by the user. It also contains three fields. Each record corresponds to one submission by the user:

Record -- remarks type, which is saved as a query string.
Created-the date and time when the user submits the form. Remoteip: the IP address of the form submitter.
In practice, you may need to collect more information about users. In this example, only the additional information of the submission time and the user IP address are recorded.

2. Preparations

After defining the above data structure and form, you can write a script. The script task is to generate a form and process the form submitted by the user.

Whether it is form generation or processing, the following three processes (tasks) are essential: the first is to determine the verification type. When the form is generated, the verification type value is obtained through the query string, read from the hidden fields of the form when processing the form. The program supports the following four types of Form Verification Methods: no verification, client JavaScript verification, and Server ASP script verification, verify both the client and the server (Code: 0 to 3 ). If a valid authentication method is not specified in the query string, the fourth authentication method is used by default. This verification processing method allows us to flexibly apply this form generation and processing system. When the client prohibits JavaScript verification, we can only execute the verification process on the server. The following code determines the verification type:

'Check the verification type
Ivaltype = request. querystring ("Val ")
If isnumeric (ivaltype) = false thenivaltype = 3
If ivaltype> 3or ivaltype <0 then ivaltype = 3
The second task is to open the database connection and create two record set objects: Rs object, which is the main record set object in this program, used to operate the definitions table; rslist object, it is 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 must first create a DSN named dynamic, the code for connecting to the database using DSN has been commented out ).

The third task is to output some static HTML code before (and after) The form script is generated (or processed), such as In addition to the code used to complete the preceding tasks, other ASP scripts in the example application may generate two types of pages: question form (see) and the results page after the form is submitted (the latter is also responsible for records of the results submitted by the user ). To determine which script to run, the simplest way is to check whether a form has been submitted: If yes, process the form; otherwise, generate the form.

'Are forms generated or processed?
If Len (request. Form) = 0 then
'Generate a form
...
Else
'Process the form
...
End if
3. dynamically generate forms

When a form is generated, the program generates the corresponding form HTML code and JavaScript code in sequence according to the definition records of each input field in the definitons table. In HTML code, text labels must be generated first:

Shtml = shtml & vbtab & "<tr>" & vbcrlf & vbtab
Shtml = shtml & "<TD valign =" & CHR (34) & "TOP" & CHR (34)
Shtml = shtml & ">" & vbcrlf & vbtab

Shtml = shtml & "<B>" & Rs. Fields ("label ")
Then the program checks whether the current input field is required. If necessary, an asterisk (indicating that the value must be entered) is added after the label text, and a javascript code is generated to verify the value. For single-choice buttons or selection lists, You need to further check that you have selected an option. For all other input types, you only need to check that the input value is not empty.

The text tag is the input element of the form. The HTML code of these elements is generated based on the type and attribute specified in the definitions table. The next step is to generate the JavaScript code to execute the client verification task according to the input value. In this example, only the numeric value needs to be further checked to ensure that the user input is indeed a number, and the numeric value is between the permitted maximum and minimum values. After the above Code is generated, you can end a table row (that is, an input field) and continue to process the next record of the definitions table. Once all the database records are processed, you can add the "Submit" button and "clear" button to the next step. From another perspective, the task of the program here is to generate various input fields based on database records. Each input field occupies one table row, and each table row has two units: the first unit is used to display text labels, and the second unit is used to display the input element itself (for the code, see dform. ASP ).

After the above process is completed, the form's HTML code and verification are saved to the variables shtml and sjavascript respectively using JavaScript Functions. Before writing the content to the page, the program checks whether the client requires JavaScript verification. If this verification is not required, the sjavascript variable is cleared:

If ivaltype = 0 or ivaltype = 2 then sjavascript = ""
After the body tag is output, the program outputs the following JavaScript Functions:

<Scriptlanguage = "JavaScript">
<! --
Function validate (theform ){
// Client Form Verification
<% = Sjavascript %>
Return true;
}
 
Function checkradio (objradio ){
// Whether a value in the single-choice button is selected
For (Varn = 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 (Varn = 1; n <objlist. length; n ++ ){
If (objlist. Options [N]. Selected ){
Return true;
}
}
Return false;
}
// -->
</SCRIPT>
If the client does not require Javascript verification, only the "Return true" statement is left in the validate function. The two static JavaScript Functions (checkradio and checklist) in the above Code are used to verify the single-choice buttons and drop-down lists. When the two input fields need to be verified, the validate function calls them.

Now you can write the form to the page:

<Form action = "./dform. asp" method = "Post" name = "myform" onsubmit = "Return validate (this)">
Here, the form submission operation is executed only when the validate function returns true. Therefore, when the client JavaScript verification function is disabled, the validate function automatically returns true.

Next we will add a hidden domain named Val. As described above, this value indicates the Form validation mode.

<Input type = "hidden" name = "Val" value = "<% = ivaltype %>">
When a user submits a form, the processing script determines whether to perform server-side Verification Based on this value.

The table tag and table title are output. The title is stored in the variable stitlelabel. The value is initialized when the script starts to run:

<Table border = "0">
<Tr>
<TD colspan = "2" align = "center">
<H2> <% = stitlelable %> </H2>
</TD>
</Tr>
As an improvement measure, you can add a field formid in the definitions, lists, and records tables. 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 above stitlelabel, we can use another table (such as forms) to save it.

Next to the table tag and table title, the program outputs the HTML form and the Code for the "Submit" and "clear" buttons. After that, the program checks whether the shtml string contains "*". If the string contains "*", it indicates that there is a required input in the form. At this time, a footer is output to indicate the meaning of the asterisk.

<% = Shtml %>
<Tr>
<TD colspan = "2" align = "center">
<Input type = "Submit" value = "Submit Form"> <input type = "reset" value = "clear">
</TD>
<%
'Whether a form field must be input exists. If yes, the output form footer explains '*'.
If instr (shtml, "*") then
%>
</Tr>
<TD colspan = "2" align = "center">
<Font size = "2"> Note: Values marked with star numbers must be entered. </Font>
</TD>
</Tr>
<%
End if
%>
</Table>
</Form>
So far, the form generation task has been completed.

4. process submitted results

The remaining tasks of ASP scripts are form processing on the server, including verifying, saving the results to the database, and displaying the "Submission succeeded/failed" page. This part of Form Verification Code uses a string variable sbadform, which is used by the program to save error information. If sbadform is empty at the end of the verification process, the form submitted by the user is legal; otherwise, the form is rejected and the sbadform is returned to the browser.

Regardless of the Form validation mode, checking for http_referer is a good habit. This check prevents scripts from being stolen. To check whether a post is a page or script from the website, you only need to compare two server variables:

If instr (request. servervariables ("http_referer "),_
Request. servervariables ("http_host") = 0 then

Sbadform = "<li> the position where the form is submitted is incorrect. "& Vbcrlf
End if
If the hidden field indication of a form must be verified on the server side, the program traverses the form definition database record for the corresponding check. The process is very similar to the form generation, but at this time the program is a verification form, add invalid input values to sbadform. For specific code, see dform. asp.

The program finally checks whether sbadform is empty. If it is not blank, form submission is rejected and sbadform is written to the browser. If sbadform is empty, add a record in the records table to save the form data. You need to delete the hidden field Val before saving the form content. This hidden field is always the first input field of the form:

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 ("Rs. Close
Else
Response. Write ("Response. Write (vbcrlf & sbadform)
End if
End if
This is the whole process of form processing on the server. Based on whether a submitted form exists, we can encapsulate the code of the previously generated form and the Code for processing the form with the if statement, so that the two scripts share some public code, for example, HTML document headers, database object creation, and resource release.

In general, dform. asp only provides the core functions required for dynamic form generation and verification, ignoring the handling of many details. For example, you can add a table to manage multiple forms so that the script can manage, generate, and process specified forms. Another obvious deficiency is the addition, deletion, and update of form definition data, as well as the access to user-submitted result data. Such features can be implemented in an independent program, and in most cases, traditional applications (non-B/S-structured applications) can be made ). Finally, dform. asp supports a limited number of input fields. In practice, there may be other form input requirements, such as a dedicated e-mail address input box. However, for websites that often need to update forms, the dynamic form generation and dynamic verification functions discussed in this article are indeed very useful.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.