Generation and verification of ASP+JS processing complex forms

Source: Internet
Author: User
Tags definition chr empty header html form odbc numeric value valid
Asp+|js

A complex form here is a form that contains many different types of input, such as a drop-down list box, a single line of text, multi-line text, numeric values, and so on. There is a need to have a dynamic build program for a form when you often need to replace such forms. This article is about a system that uses a database to save forms to define data, to dynamically generate form HTML code with ASP scripts, and to validate form input scripts.

  Definition of database table structure

Forms such as weekly surveys are often visible on the web, which is a form that needs to be updated frequently. If you have a program that dynamically generates forms and their validation scripts, you can significantly reduce the amount of work that you do to make these forms.

In the example of dynamic form generation and validation in this article, we use an Access database to store the definition information about the form, and for simplicity, the data that the user enters into the form is saved to the same database. It takes two tables to define a form: The first table (definitons) is used for the definition of the form input field, and the second table (Lists) Saves additional information about each input field, such as selecting a list.

The table definitons contains the following fields:

    • fieldname--the variable name that gives the form input field
    • label--is a text label that shows the prompt text in front of the input field
    • type--A single character that represents the form input field and the type of the input value

Specifically as follows:

(t) text input box, that is, < input type= "text" >.

(n) Text entry box, but requires a numeric value to be entered.

(m) Memo-type content, for comments or other large amounts of text input, which is a multiple-line edit box.

(b) Require the importation of "yes" or "no". A check box is used in this implementation to get this input, and the text label for the check box is yes. If the user selects it, the return value is "on".

(r) radio button.

(l) Drop-down list box.

min--is valid only for numeric input values, where the minimum value is given. In this example, there is an age-numeric input box with a minimum value of 1.

max--The value of this field is related to the form of the input field. For a numeric input box, it represents the maximum allowable value. For example, the max value of "age" is 100. For a text entry box, Max represents the maximum number of characters allowed. For a multiline edit box, Max represents the number of lines of text in the visible area.

required--indicates whether it must be entered. If the value of this type is not entered, the input validator will report an error. In the form, the value that must be entered is marked with an asterisk and prompts the user with a footnote that the class value must be entered.

The sample form in this article is an ASP programmer questionnaire, which is defined in the Definitons table as follows:

FieldName Label Type Min Max Required

Name text (t)-50 No

Age number (n) 1 100 No

Sex Sex radio button (r)--Yes

e-mail address text (t)--IS

Language programming language Drop-down list box (l)--No

Table lists is used to save some additional information about the input field definition, in this case there are "Sex" and "Languages" two input values to use. The table lists is very simple and contains only the following three fields:

fieldname--which form input field the current record belongs to

value--the value of the selected item

label--the prompt text for the selected item that the user sees

The input field "Sex" can only be selected from two values: "Male" or "female". "Language" lists several programming languages that can be applied to the ASP environment, including: Vbscript,javascript,c,perl and "other".

The third table, "Records," saves the user-submitted content, and it also contains three fields, each of which corresponds to a user's commit:

record--memo type, user input saved as a query string.

created--the date and time when the user submitted the form. remoteip--the IP address of the form submitter.

In the actual application may want to gather more information about the user, for the simple account, this example only records the submission time and the user IP address these two additional information.

  Ii. preparatory work

Once you have finished defining the data structures and forms, you can then write the script. The task of the script is to generate the form and process the user-submitted form.

Whether the form is generated or processed, the following three processes (tasks) are essential: the first is to determine the type of validation, the validation type values are obtained from the query string when the form is generated, and the hidden fields are read from the form when the form is processed. There are four types of forms authentication that the program supports: No authentication, client JavaScript validation, server-side ASP script validation, client and server-side validation (code-named 0 to 3 respectively). If you do not specify a valid authentication method in the query string, the fourth method of authentication is default. This validation process allows us to flexibly apply this form generation and processing system that can be performed only on the server side when the client prohibits JavaScript validation. The following is the code that determines the type of validation:

Check validation type

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 the database connection and create two Recordset objects: Rs Object, which is the main recordset object in this program to manipulate the definitions table; Rslist object that is used primarily to read data from the lists table. The sample program provides two types of database connection methods: Use ODBC DSN or do not use ODBC DSN (you need to create a DSN named dynamic when you use DSN, the code that uses the DSN connection database has been commented out).

The third task is to output some static HTML code, such as < head >

In addition to the code that completes the above task, the remaining ASP scripts in the example application might generate two types of pages: A question form (see above) and a result page that appears after the form is submitted (the latter is also responsible for the user's record of submitting results). The easiest way to determine which part of the script to run is to check whether the form has been submitted: If so, the form is processed;

Generate a form or process a form?

If Len (Request.Form) = 0 Then
' Generate a form
... Slightly...
Else
' Process a form
... Slightly...
End If

  Iii. Dynamic generation of forms

When the form is generated, the program defines the records according to each input field in the Definitons table, generating the corresponding form HTML code and JavaScript code in turn. The first thing to generate in the HTML code is the text label:

SHTML = SHTML & VbTab & "< TR >" & vbCrLf & VbTab & VbTab
SHTML = SHTML & "< TD valign=" & Chr (+) & "Top" & Chr (34)
SHTML = SHTML & ">" & vbCrLf & VbTab & VbTab & VbTab
SHTML = SHTML & "< B >" & RS. Fields ("Label")

The program then checks whether the current input field must be entered. If necessary, add an asterisk after the label text (indicating that the value must be entered), and generate the appropriate JavaScript code to validate the value that must be entered. For radio buttons or select lists, you need to check further that the user does select an option, and for all other input types, just check that the input value is not empty.

The text label immediately follows the input elements of the form, and the HTML code for those 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 validation tasks based on the input value requirements. For this example, only the numeric value needs to be examined further to ensure that the user's input is indeed a number, and that the numeric value is between the maximum allowable and the minimum value. After you generate the above code, you can end a table row (that is, an input field) to continue processing the next record of the definitions table. Once all the 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 a different perspective, the task here is to generate each input field based on the database records, each input field occupies a table row, each table row two units: the first cell is used to display the text label, the second unit displays the INPUT element itself (code see DFORM.ASP).

After the above process is complete, the form's HTML code and validation are saved to the variable shtml and Sjavascript, respectively, with JavaScript functions. Before writing the content to the page, the program checks to see if the client requires JavaScript validation and clears the Sjavascript variable if no such validation is required:

If ivaltype = 0 Or ivaltype = 2 Then sjavascript = ""

After the body tag is output, the program prints the following JavaScript function:

< SCRIPT language= "JavaScript" >
<!--
function Validate (theform) {
Client form Validation
<%=sjavascript% >
return true;
}

function Checkradio (objradio) {
Whether a value is selected in the radio button
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 select 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, then the Validate function has only one "return true" statement. The following two static JavaScript functions (Checkradio and checklist) in the preceding code are used to validate radio buttons and Drop-down list boxes, which are invoked by the validate function when the two input fields need to be validated.

You can now start writing the form to the page:

  < FORM action= "./dform.asp" method= "POST" name= "MyForm" >

Here, the form submission operation is performed only if the Validate function returns TRUE. Therefore, when client JavaScript validation is turned off, the Validate function automatically returns TRUE.

The next thing to add is a hidden field named Val. As mentioned earlier, this value indicates the validation mode of the form.

  < INPUT type= "HIDDEN" Name= "val" value= "<%=ivaltype% >" >

When a user submits a form, the processing script determines whether to perform server-side validation based on that value.

Then the output is the table tag and the table header. The caption is saved in the variable Stitlelabel, which is initialized when the script starts executing:

< TABLE border= "0" >
< TR >
< TD colspan= "2" align= "CENTER" >
< H2 ><%=stitlelable% >

</td >
</tr >

As an improvement measure, you can add a field formid to tables definitions, lists, and records. Formid uniquely identifies a form so that a program can define multiple forms at the same time, and user responses that hold multiple forms. As for the above Stitlelabel, we can use another table (such as forms) to save.

Immediately after the table tag and the table caption, the program outputs the HTML form and the code for the submit, clear button. After this, the program checks to see if the shtml string contains "*", which, if included, indicates what must be entered in the form, and then prints a footnote to explain what the asterisk means.

<%=shtml% >
< TR >
< TD colspan= "2" align= "CENTER" >
< INPUT type= "submit" value= "Submission Form" > < INPUT type= "reset" value= "clear" >
</td >
<%
' Whether there is a form field that must be entered, if it exists, the output form footnote explanation ' * ' means
If InStr (SHTML, "*") Then
% >
</tr >
< TD colspan= "2" align= "CENTER" >
< FONT size= "2" > Note: A value marked with an asterisk must be entered. </font >
</td >
</tr >
<%
End If
% >
</table >
</form >

The form's build task has thus far been completed.

  Iv. Processing of submission Results

The remaining tasks for ASP scripts are server-side form processing, including validation, saving the results to the database, and displaying the submit success/failure page. In this part of the form validation code is used a string variable sbadform, which the program uses to save the error message. If the sbadform is null at the end of the validation process, the form submitted by the user is legitimate, otherwise the form's submission is rejected and the Sbadform is returned to the browser.

Checking Http_referer is a good habit, regardless of the type of validation that the form takes. This check prevents the script from being embezzled. To check whether a post comes from a page or script on this site, simply compare the two server variables:

If InStr (Request.ServerVariables ("Http_referer"), _
Request.ServerVariables ("http_host") = 0 Then
Sbadform = "< LI > form submitted from incorrect location. "& VbCrlf
End If

If the form's hidden field indicates that server-side validation is required, the program traverses the form definition database records for a corresponding check, and the procedure is very similar to the form's generation, except that the program is validating the form and adding illegal information to the sbadform. See dform.asp for specific code.

The program finally checks to see if Sbadform is empty. If not null, the 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. You need to remove the hidden field Val before saving the contents of the form, which is always the first input field in 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 ("< H1 > Thank .

Rs. Close
Else
Response.Write ("< H1 > form submission failed. </H1 > ")
Response.Write (VbCrLf & Sbadform)
End If
End If

This is the whole process of server-side form processing. Based on the existence of the submitted form, we can encapsulate the code that generated the form in front of it and the Code processed here with the 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 the database object, and the release of the resource.

In general, dform.asp only has the core functions necessary for dynamic form generation and verification, ignoring the processing of many detail problems. For example, the problem of multiple forms mentioned earlier: Adding a table to manage multiple forms makes the script capable of managing, generating, and processing the specified forms. Another obvious lack is that the form defines data additions, deletions, and updates, as well as access to user-submitted results data, which can be implemented in a separate program, and in most cases can be made into traditional applications (non b/s applications). Finally, the type of input domain supported by dform.asp is also limited, there may be other form input requirements in practice, such as the special e-mail address input box. However, the form dynamic generation and dynamic validation features discussed in this article are really useful for web sites that often want to update the form.



Related Article

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.