Export (0) Print
Expand All

Walkthrough: Validating User Input in a Web Forms Page

As with any input form, Web Forms pages require you to make sure that users are entering information that is valid, is in the right format, and so on. To make this common task easier, you can use validation controls created especially for Web Forms pages. Validation controls allow you to check for required entries, data types, ranges, patterns, and specific values by simply setting properties. The controls perform checking automatically and include a variety of ways for displaying error information to users. For an overview, see Web Forms Validation.

Security Note   By default, the Web Forms page automatically validates that malicious users are not attempting to send script to your application. For more information, see Scripting Exploits.

This walkthrough illustrates a simple Web Forms page that you might create as a simple registration page. The page includes text boxes to allow users to enter a login name, a birth date, a password, and a repeat of the password. You will add validation controls to the page to be sure that users enter values into all the boxes and that the values are formatted correctly.

In order to complete this walkthrough, you will need sufficient permissions to be able to create ASP.NET Web application projects on the computer where your Web server is.

The walkthrough is split into a number of smaller pieces:

  • Creating the basic form by creating a project and Web Forms page and adding the input controls and labels.
  • Adding the validation controls. You will validate for required entries, that the user has entered a valid login name and date, and that the passwords match.
  • Testing.

When you have finished the walkthrough, you will have a form that looks similar to the following.

a0z2h4sw.vbwebformsvalidationcontrolswalkthrough(en-us,VS.71).gif

Creating the Basic Form

You can start by creating a form with input controls on it.

Creating the Form

The first step is to create a form that you will later add validation controls to. Start by creating a new Web application project and Web Forms page.

To create the project and form

  1. On the File menu, point to New, and then click Project.
  2. In the New Project dialog box, do the following:
    1. In the Project Types pane, choose either Visual Basic Projects or Visual C# Projects.
    2. In the Templates pane, choose ASP.NET Web Application.
    3. In the Location box, enter the complete URL for your application, including http://, the name of the server, and the name of your project. The Web server must have IIS version 5 or later and the .NET Framework installed on it. If you have IIS on your computer, you can specify http://localhost for the server. (If you normally use a proxy server to access the Internet, you might need to configure Internet Explorer to bypass the proxy server in order to use localhost.)

      When you click OK, a new Web Forms project is created at the root of the Web server you specified. In addition, a new Web Forms page called WebForm1.aspx is displayed in the Web Forms Designer in Design view.

      Tip   If you have trouble creating a Web application project, see Web Access Failed Dialog Box.
  3. If the page is not already in grid mode, use the Properties window to set the document object's pageLayout property to GridLayout.

    This step is optional, but makes it easier to lay out the form. If you prefer to work in flow layout, you can, but you might have to make minor adjustments to where the controls appear on the page. The page will work the same way in either case.

Adding Input Controls

For this walkthrough, which assumes that you are creating a simple registration page, you will add controls to allow users to enter a name (an e-mail address), a birth date, and a password. Users enter the password twice to confirm it.

To add the controls

  1. From the Web Forms tab of the Toolbox, add the following controls to the form, setting their ID property as indicated:
    ControlPurposeID
    TextBoxEnter user nametxtName
    TextBoxEnter birth datetxtBirthdate
    TextBoxEnter passwordtxtPassword
    TextBoxRepeat password to confirm ittxtPasswordAgain
    ButtonSubmit formbtnRegister

    Set the button's Text property to Register.

  2. Set the TextMode property of the two password boxes to Password so that they display stars (*) as users type in them.
  3. Add labels in front of the text boxes to indicate their function. If the Web Forms page is in grid mode, add Label controls in front of each text box and set their Text property. If the page is in flow mode, simply type static text in front of each box.
  4. Adjust the font, size, and layout of the controls to your liking. For details about layout, see Positioning HTML Elements in Design View.

Adding Validation Controls

Now that you have created the input form, you can add validation. You do so by adding validation controls to the form, one control for each validation test you want to perform. (In all, you will add seven validation controls to cover all the tests you should perform plus a control to display errors.) The validation tests you will perform are these:

  • Required fields. You want to be sure that users enter values into all four boxes.
  • Name format. For this walkthrough, you will check that the user's login name follows the pattern of typical e-mail names: name@domain.xxx. In this walkthrough, you will not validate that the e-mail name the user provides belongs to a valid e-mail account.
  • Date format. You will validate that the user's entry for birth date is a valid date. (In this walkthrough, you will not validate that the date falls within a specific range.)
  • Password match. You will validate that the passwords that the user supplies in the two password boxes match.

Checking For Required Fields

You want to be sure that users enter values into all four text boxes — that is, all four text boxes are required fields.

To check for required fields

  1. From the Web Forms tab of the Toolbox, drag a RequiredFieldValidator control onto the form, next to the txtName text box.
  2. Select the validation control and in the Properties window, set the following properties.
    PropertySetting
    ControlToValidatetxtName

    This indicates that the validator will check the contents of the name field.

    Text* (star)

    This is the text that will be displayed where the validator control is now. (It is common to put a red star next to an input box containing errors.)

    ErrorMessageEmail name is required.

    This text will be displayed in a summary on the page.

  3. If you like, set the font, color, and formatting properties for the validation control. These properties affect how errors are displayed.
  4. Repeat Steps 1 through 3 for the other three text boxes, creating three more RequiredFieldValidation controls with the following settings.
    ControlSettings
    RequiredFieldValidator2
    • ControlToValidate: Set to txtBirthdate
    • Text: *
    • ErrorMessage: You must enter a birth date.
    RequiredFieldValidator3
    • ControlToValidate: Set to txtPassword
    • Text: *
    • ErrorMessage: You must enter a password.
    RequiredFieldValidator4
    • ControlToValidate: Set to txtPasswordAgain
    • Text: *
    • ErrorMessage: Re-enter the password to confirm it.

Checking Name Format

For the walkthrough, you are assuming that the user should enter an e-mail address as the registration name. Although you cannot check that the name represents a valid e-mail account, you can check that the name conforms to typical e-mail address format (such as name@domain.com). This catches entry errors that users often make, such as forgetting to enter the ".com" portion of their e-mail address.

To check for patterns such as this, you use a validator control that incorporates a regular expression. If you know regular expression syntax, you can create your own pattern-matching expressions. However, you can also choose from a list of predefined regular expressions, including those to check for e-mail addresses, phone numbers, and postal codes.

When you add this validation control, you will have two controls for the name box; the contents of the box must pass both checks to be considered valid. When you have multiple validators for a single control, you generally want them to display their text (typically, a star) in the roughly the same location, no matter which validation check fails. You can specify this by setting the validator control's Display property. For more information, see Validation Error Message Layout for ASP.NET Server Controls.

To check name format

  1. From the Web Forms tab of the Toolbox, drag a RegularExpressionValidator control next to the txtName box.
  2. Select the validation control and in the Properties window, set the following properties.
    PropertySetting
    ControlToValidateTxtName
    Text* (star)
    ErrorMessageName must be in the format name@domain.xxx.
    ValidationExpressionFrom the list, select Internet E-mail Address. Note that this sets the property value to a regular expression.

Checking Date Format

You want to be sure that users enter a valid date for the birth date field. You can do this with a validation control that performs two functions at once: it checks that the user has entered a date (by data type) and it compares that the date is later than a specified minimum date.

To check date format

  1. From the Web Forms tab of the Toolbox, drag a CompareValidator control next to the txtBirthdate box.
  2. Select the validation control and in the Properties window, set the following properties.
    PropertySetting
    ControlToValidateTxtBirthdate
    Text* (star)
    ErrorMessageBirth date is not a valid date.
    ValueToCompare1900/01/01

    (Or any other minimum date.)

    Note   Enter the date to compare in the format yyyy/mm/dd; this ensures that it will be interpreted properly for all culture settings. Users must enter the date using only numbers for the month.
    OperatorGreater Than
    TypeDate
    DisplayDynamic

Checking for Password Match

As is done often, your registration form asks users to type their password twice to confirm that that is what they want to enter. You can check this using the same validation control you used for the date — a comparison control — but instead of checking against a specific value, you will compare the value of one field — the second password box — against what they typed into the first password box.

Security Note   Using a TextBox control set for passwords can help ensure that other people will not be able to determine a user's password if they observe the user entering it. However, the password text entered is not encrypted in any way, and you should protect it as you would any other confidential data. For example, for maximum security when posting a form with a password in it, you might use secure sockets layer (SSL) and encryption. For more information, see Web Application Security at Run Time.

To check for password match

  1. From the Web Forms tab of the Toolbox, drag a CompareValidator control next to the txtPasswordAgain box.
  2. Select the validation control and in the Properties window, set the following properties.
    PropertySetting
    ControlToValidateTxtPasswordAgain
    Text* (star)
    ErrorMessageThe passwords do not match.
    ControlToCompareTxtPassword
    OperatorEqual
    DisplayDynamic

Displaying Validation Errors

One step remains. You have configured the validation controls so that they display a red star next to an input box containing an error. However, this might not give users enough information. For example, they might realize that they have entered a bad registration name, but might not be able to figure out what is wrong with it.

To display details about validation errors, you can use a summary control. The control displays the value of the ErrorMessage property of any validation control that has detected an error. If there is more than one error, the summary control can display them all, either as bulleted items, in a simple list, or as a paragraph of text.

To display validation errors

  1. From the Web Forms tab of the Toolbox, drag a ValidationSummary control onto the form. Position the control someplace where it has room to display several lines of text.
  2. If you want to display errors in a format other than bulleted items, select a different display option for the DisplayMode property.
  3. Set the Font and ForeColor properties to format the error message text.
  4. You are done adding validation controls. Now you can test to see how they work.

Testing Validation

You want to test the Web Forms page with different values to see the effect of the validation controls.

To test the validation controls

  1. In Solution Explorer, right-click the name of your form and choose View in Browser.
  2. When the page is displayed, enter various values into the boxes. To check the birth date, enter a date that is invalid for the locale of your Web server.

    Each time you make an error, a star should appear next to the box containing the error.

  3. Click Register.

    If there are any errors, the error message text appears in the summary control. (Red stars appear and disappear immediately as you work with the fields.)

    Note   Required fields are checked the first time only when you submit the form, so that users are not forced to enter data into the form in a specific order. However, after the first time the form is submitted, errors are reported until the field is filled in.

If you are not seeing the errors you expect to see, review the settings for each of the validation controls and try again.

Next Steps

The validation you added in this walkthrough to the Web Forms page illustrates the basic concepts of Web validation controls. There is more you can do with validation controls, both with their basic functionality as well as in code. You could expand on the walkthrough in these ways:

  • Check that the user enters a birth date earlier than today by adding a second CompareValidator control and setting its operator to LessThan and its comparison value to today. You can use a data-binding expression to set the value. Although you are not binding the validator control to data, you are taking advantage of the fact that data binding expressions are evaluated before the control is rendered. The ASP.NET syntax for the control might look like this:
    <asp:CompareValidator id=c1 
    ValueToCompare='<%# DateTime.Today.ToShortDateString() %>' 
    ControlToValidate="txtBirthDate" Operator="LessThan" Type="Date" Text="*" runat="server" />
    
    Note   You must call the validator control's DataBind method to resolve the expression.
  • Check the length of the password to be sure it meets a certain minimum number of characters. You can do this with a RegularExpressionValidator control. There is no predefined expression that checks for a minimum number of characters. You can use an expression such as the following, which requires five or more characters:
    ^[\w]{5,}
    
  • Test validation in code. Each validation control sets a flag that you can test programmatically. This complements the visual feedback that the controls provide; by testing for valid input in code, you can determine how to proceed (or not proceed) in your application. For details, see Validating Programmatically for ASP.NET Server Controls.
  • Learn about the security issues associated with Web Forms. For details, see Overview of Web Application Security Threats.

See Also

Introduction to Validating User Input in Web Forms

Show:
© 2015 Microsoft