Partager via


Using Forms and Processing User Input

By using the ASP Request Object object, you can create simple, yet powerful scripts for collecting and processing data gathered with HTML forms. In this topic, you will not only learn how to create basic form processing scripts, but also acquire useful techniques for validating form information, both on your Web server and at the user's browser.

About HTML Forms

HTML forms, the most common method for gathering Web-based information, consist of arrangements of special HTML tags that render user interface elements on a Web page. Text boxes, buttons, and check boxes are examples of elements that enable users to interact with a Web page and submit information to a Web server.

For example, the following HTML tags generate a form where a user can enter their first name, last name, and age, and includes a button for submitting information to a Web server. The form also contains an hidden input tag (not displayed by the Web browser) that you can use to pass additional information to a Web server.

<FORM METHOD="Get" ACTION="Profile.asp"> 
<INPUT TYPE="Text" NAME="FirstName">  
<INPUT TYPE="Text" NAME="LastName"> 
<INPUT TYPE="Text" NAME="Age"> 
<INPUT TYPE="Hidden" NAME="UserStatus" VALUE="New"> 
<INPUT TYPE="Submit" VALUE="Enter"> 
</FORM> 

Detailing the complete set of HTML form tags is outside the scope of this topic, however, there are numerous sources of information that you can use to learn about creating useful and engaging HTML forms. For example, use your Web browser's source viewing feature to examine how HTML forms are created on other Web sites. Also, visit the Microsoft MSDN Online Web site to learn innovative ways of using HTML forms with other Internet technologies.

Processing Form Inputs with ASP

After creating an HTML form, you will need to process user input, which means sending the information to an .asp file for parsing and manipulation. Once again, examine the HTML code from the previous example. Notice that the <FORM> tag's ACTION attribute refers to a file called Profile.asp. When the user submits HTML information, the browser uses the POST method to send to the information to an .asp file on the server, in this case Profile.asp. The .asp file may contain scripts that process information and interact with other scripts, COM components, or resources, such as a database.

Using ASP, there are three basic ways to collect information from HTML forms:

  • A static .htm file can contain a form that posts its values to an .asp file.

  • An .asp file can create a form that posts information to another .asp file.

  • An .asp file can create a form that posts information to itself, that is, to the .asp file that contains the form.

The first two methods operate in the same way as forms that interact with other Web server programs, except that with ASP, the task of collecting and processing form information is greatly simplified. The third method is a particularly useful and will be demonstrated in the Validating Form Input section.

Getting Form Input

The ASP Request object provides two collections that facilitate the task of retrieving form information sent with as a URL request.

The QueryString Collection

The Request.QueryString Collection collection retrieves form values passed to your Web server as text following a question mark in the request URL. The form values can be appended to the request URL by using either the HTTP GET method or by manually adding the form values to the URL.

For example, if the previous form example used the GET method (METHOD="GET") and the user typed Clair, Hector, and 30, then the following URL request would be sent to the server:

http://Reskit/Workshop1/Painting/Profile.asp?FirstName=Clair&LastName=Hector&Age=30&UserStatus=New 

Profile.asp might contain the following form processing script:

Hello <%= Request.QueryString("FirstName") %> <%= Request.QueryString("LastName") %>.  
You are <%= Request.QueryString("Age") %> years old! 

<% 
  If Request.QueryString("UserStatus") = "New" Then  
    Response.Write "This is your first visit to this Web site!" 
  End if     
%> 

In this case, the Web server would return the following text to the user's Web browser:

Hello Clair Hector. You are 30 years old! This is your first visit to this Web site! 

The QueryString collection also has an optional parameter that you can use to access one of multiple values that appear in the URL request (using the GET method). You can also use the Count property to count the number of times that a specific type of value appears.

For example, a form containing a list box with multiple items can generate the following request:

http://Reskit/OrganicFoods/list.asp?Food=Apples&Food=Olives&Food=Bread 

You could use the following command to count multiple values:

Request.QueryString("Food").Count 

To display the multiple values types, List.asp could contain the following script:

<% 
  lngTotal = Request.QueryString("Food").Count 
  For i = 1 To lngTotal 
    Response.Write Request.QueryString("Food")(i) & "<BR>" 
  Next 
%> 

The preceding script would display:

Apples 
Olives 
Bread 

You can also display the entire list of values as a comma-delimited string by using the following:

<% Response.Write Request.QueryString("Item") %> 

This would display the following string:

Apples, Olives, Bread 

Form Collection

When you use the HTTP GET method to pass long and complex form values to a Web server, you run the risk of losing information. Some Web servers tend to restrict the size of the URL query string, so that lengthy form values passed with the GET method might be truncated. If you need to send a large amount of information from a form to a Web server, you should use the HTTP POST method. The POST method, which sends form data in the HTTP request body, can send a an almost unlimited number of characters to a server. You can use the ASP Request object's Request.Form Collection collection to retrieve the values sent with the POST method.

The Form collection stores values in a manner similar to the QueryString collection. For example, if a user filled out a form by entering a long list of names, then you could retrieve the food names with the following script:

<% 
  lngTotal = Request.Form("Food").Count 
  For i = 1 To lngTotal  
   Response.Write Request.Form("Food")(i) & "<BR>" 
  Next 
%> 

Validating Form Input

A well-designed Web form often includes a client script that validates user input prior to sending information to the server. Validation scripts can check for such things as whether the user entered a valid number or whether a text box was left empty. Imagine that your Web site includes a form that enables users to compute the rate of return on an investment. You will probably want to verify whether a user has actually entered numerical or text information in the appropriate form fields, prior to sending potentially invalid information to your server.

In general, it's good practice to do as much form validation as possible on the client side. Beyond prompting users more quickly about input errors, client-side validation yields faster response times, reduces server loads, and frees bandwidth for other applications.

The following client-side script validates user input (in this case, the script determines whether an account number entered by the user is actually a number) prior to sending information to the server:

<SCRIPT LANGUAGE="JScript"> 

function CheckNumber() 
{            
 if (isNumeric(document.UserForm.AcctNo.value)) 
   return true 
 else 
 { 
   alert("Please enter a valid account number.") 
   return false 
 }       
} 

//Function for determining if form value is a number. 
//Note:  The JScript isNaN method is a more elegant way to determine whether 
//a value is not a number. However, some older browsers do not support this method. 
function isNumeric(str) 
{ 
  for (var i=0; i < str.length; i++) 
        { 
    var ch = str.substring(i, i+1) 
    if( ch < "0" || ch>"9" || str.length == null) 
                { 
      return false 
    } 
  } 
  return true 
}    
</SCRIPT> 

<FORM METHOD="Get" ACTION="balance.asp" NAME="UserForm" ONSUBMIT="return CheckNumber()"> 

    <INPUT TYPE="Text"   NAME="AcctNo"> 
    <INPUT TYPE="Submit" VALUE="Submit"> 

</FORM> 

If form validation requires database access, however, you should consider using server-side form validation. A particularly advantageous way of carrying out server-side validation is to create a form that posts information to itself. That is, the .asp file actually contains the HTML form that retrieves user input. (Remember, you can use ASP to interact with client-side scripts and HTML. For more information, see Interacting with Client-Side Scripts.) The input is returned to the same file, which then validates the information and alerts the user in case of an invalid input.

Using this method of processing and validating user input can greatly enhance the usability and responsiveness of your Web-based forms. For example, by placing error information adjacent to the form field where invalid information was entered, you make it easier for the user to discover the source of the error. (Typically, Web-based forms forward requests to a separate Web page containing error information. Users who do not immediately understand this information may become frustrated.)

For example, the following script determines whether a user entered a valid account number by posting information to itself (Verify.asp) and calling a user defined function that queries a database:

<%  
  strAcct = Request.Form("Account") 
  If Not AccountValid(strAcct) Then    
    ErrMsg = "<FONT COLOR=Red>Sorry, you may have entered an invalid account number.</FONT>" 
  Else 
Process the user input 
    . 
    . 
    .    
    Server.Transfer("Complete.asp") 
  End If 

  Function AccountValid(strAcct) 
A database connectivity script or component method call goes here. 
  End Function  
%> 

<FORM METHOD="Post"  ACTION="Verify.asp">    
Account Number:  <INPUT TYPE="Text" NAME="Account"> <%= ErrMsg %> <BR>  
<INPUT TYPE="Submit">          
</FORM> 

In this example, the script is located in a file named Verify.asp, the same file that contains the HTML form; it posts information to itself by specifying Verify.asp in the ACTION attribute.

ms525182.alert_caution(en-us,VS.90).gifImportant Note:

If you are using JScript for server-side validation, be sure to place a pair of empty parentheses following the Request collection item (either QueryString or Form) when you are assigning the collection to a local variable. Without parentheses, the collection returns an object, rather than a string. The following script illustrates the correct way to assign variables with JScript:

<% 
   var Name = Request.Form("Name")(); 
   var Password = Request.Form("Password")(); 

  if(Name > "") 
  { 
     if(Name == Password) 
      Response.Write("Your name and password are the same.") 
  else 
      Response.Write("Your name and password are different."); 
  } 
%> 

VBScript exhibits the same behavior if the collection contains multiple values that are comma-separated or indexable. This means that for both VBScript and JScript, in addition to placing a pair of empty parentheses following the Request collection item, you will need to specify the index of the desired value. For example, the following line of JScript returns only the first of multiple values for a form element:

var Name = Request.Form("Name")(1); 

A common use of intranet and Internet server applications is to accept user input by implementing a form in your Web page. ASP includes the following two collections in the Request object to help process form information: the QueryString collection and the Form collection.

Warning

Accepting form input from clients gives malicious users a chance to send potentially unsafe characters to attack your Web application in any of the following ways:

  • Strings that are too long for you application to handle can cause your application to fail or write over existing data.

  • Strings that contain invalid characters can cause your application to fail or perform unexpected actions.

  • If your Web application is accessing a database, a carefully engineered string of characters can add or delete records from your database.

A general method of protection against these kinds of attacks is to Server.HTMLEncode all form input when your Web page accesses the input. Another method is to write a short function that tests form input for invalid characters. This tutorial uses the Server.HTMLEncode method. However, more information can be found by reading chapter 12 of Writing Secure Code, and using Checklist: ASP Security when you create your ASP applications.

In this lesson, you create an HTML page that accepts user input in an HTML form and sends the user input back to the Web server to the same page. The Web server then displays the user input. Later in this module, you use this knowledge about forms to build a guest book application that uses ASP scripting. To complete this lesson, you perform the following tasks:

  • Example 1: Display a selection of button elements in a form.

  • Example 2: Display text box elements in a form, accept the user input from the form, and display the user input on the Web page.

Example 1: Buttons

Forms can contain many different kinds of elements to help your users enter data. In this example, there are five input form elements called buttons. There are many types of buttons including RADIO buttons, SUBMIT buttons, RESET buttons, CHECKBOX buttons, and TEXT buttons.

After the user enters information in a form, the information needs to be sent to your Web application. When a user clicks the button labeled "Submit" in your Web page, the form data is sent from the client to the Web page that is listed in the ACTION element of the form tag. This Web page doesn't need to be the same as the calling page. In this example, the Web page listed in the ACTION element is the same as the calling page, which eliminates the need to call another page.

In this example, METHOD=" POST" is used to send data from the Web client's browser to the Web server. When you use METHOD=" POST" in a form, the user data ends up in the Form collection of the Request object.

Copy and paste the following code in your text editor, and save the file as Button.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing https://localhost/Tutorial/Button.asp in the address bar.

<%@ Language= &quot;VBScript&quot; %> 

  <html>  
  <head>  
  <title>Button Form</title>  
  </head>  
  <body>  
  <font face="MS Gothic">  

  <FORM NAME="Button Example" METHOD="POST" ACTION="button.asp"> 
  <H3>Computer Programming Experience:</H3>  
  <p> 
  <INPUT TYPE="RADIO" NAME= "choice" VALUE="Less than 1"> Less than 1 year.<BR>  
  <INPUT TYPE="RADIO" NAME= "choice" VALUE="1 to 5"> 1-5 years.<BR> 
  <INPUT TYPE="RADIO" NAME= "choice" VALUE="More than 5"> More than 5 years.<BR> 
  </p>  
  <p> 
  <INPUT TYPE="SUBMIT" VALUE="Submit">  
  <INPUT TYPE="RESET" VALUE="Clear Form"> 
  </p> 
  </form>  

  <% 
   'Check to see if input has already been entered.  
   dim strChoice 
   strChoice = Server.HTMLEncode(Request.Form("choice")) 

   If "" = strChoice Then 
     Response.Write "<P>(No input yet.)</P>" 
   Else 
     Response.Write "<P>Your last choice was <B>" & strChoice & "</B></P>" 
   End If 
  %> 

  </font>  
  </body>  
  </html> 

In the browser, you should see the following:

Computer Programming Experience:

Radio Button

Less than 1 year.

Radio Button

1-5 years.

Radio Button

More than 5 years. (No input yet.)

Example 2: Input Form Elements

In this example, there are three input form elements called text fields and two input form elements called check boxes. Check boxes differ from option buttons because you can select more than one. We still need the default Submit button to send the data back to the server.

In this example, METHOD=GET is used to send data from the Web client's browser to the Web server. When you use METHOD=GET in a form, the user data ends up in the QueryString collection of the Request object.

Look at the address bar after you click Submit, and you should see the elements of the QueryString displayed at the end of the URL.

Copy and paste the following code in your text editor, and save the file as Text.asp in the x:\Inetpub\Wwwroot\Tutorial directory. View the example with your browser by typing https://localhost/Tutorial/Text.asp in the address bar.

<%@ Language= &quot;VBScript&quot; %>   

  <html>  
  <head>  
  <title>Text and Checkbox Form</title> 
  </head> 
  <body> 
  <font face="MS Gothic"> 

  <FORM NAME="TextCheckbox Example" METHOD="GET" ACTION="text.asp"> 
  <H3>Please fill out this form to get information on our products:</H3> 
  <p> 
  <table> 
  <tr> 
  <td><font face="MS Gothic">Name (required)</td> 
  <td><INPUT TYPE="TEXT" NAME="name" VALUE="" SIZE="20" MAXLENGTH="150"></td> 
  </tr><tr> 
  <td><font face="MS Gothic">Company</td> 
  <td><INPUT TYPE="TEXT" NAME="company" VALUE="" SIZE="25" MAXLENGTH="150"></td> 
  </tr><tr> 
  <td><font face="MS Gothic">E-mail (required)</td> 
  <td><INPUT TYPE="TEXT" NAME="email" VALUE="" SIZE="25" MAXLENGTH="150"></td> 
  </tr> 
  </table> 

  </p> 
  <p> 
  Requesting information on our:<BR> 
  <INPUT TYPE="CHECKBOX" NAME= "info" VALUE="software">Software<BR> 
  <INPUT TYPE="CHECKBOX" NAME= "info" VALUE="hardware">Hardware <BR> 
  </p> 
  <p> 
  <INPUT TYPE="SUBMIT" VALUE="Submit"> 
  <INPUT TYPE="RESET" VALUE="Clear Form"> 
  </p> 
  </form> 

  <% 
   'Check to see if input has already been entered. 
   dim strName, strEmail, strCompany, strInfo 
   strName = Server.HTMLEncode(Request.QueryString("name")) 
   strEmail = Server.HTMLEncode(Request.QueryString("email")) 
   strCompany = Server.HTMLEncode(Request.QueryString("company")) 
   strInfo = Server.HTMLEncode(Request.QueryString("info")) 

   'Display what was entered. 
   If ("" = strName) OR ("" = strEmail) Then 
     Response.Write "<P>(No required input entered yet.)</P>" 
   Else 
     Response.Write "<P>Your are " & strName 
     If Not ("" = strCompany) Then 
       Response.Write " from " & strCompany 
     End If 
     Response.Write ". <BR>Your email address is " & strEmail 
     If Not ("" = strInfo) Then 
       Response.Write " and you would like information on " & strInfo & ".</P>" 
     End If 
   End If 
  %> 

  </font> 
  </body> 
  </html> 

In the browser, you should see the following:

Please fill out this form to get information about our products:

Name (required)

Text Box

Company

Text Box

E-mail (required)

Text Box

Requesting information about our:

Check Box

Software

Check Box

Hardware

(No required input entered yet.)