Input Validation


When users enter data, it should be checked to see that the data is valid. The check can happen on the client and on the server. Checking the data on the client can be done by using JavaScript. However, if the data is checked on the client using JavaScript, it should also be checked on the server, because you can never fully trust the client. It is possible to disable JavaScript in the browser, and hackers can use different JavaScript functions. It is awfully necessary to check the data on the server. Checking the data on the client as well leads to better performance, as no round trips occur to the server until the data is validated on the client.

With ASP.NET it is not necessary to write the validation functions yourself. Many validation controls exist that create both client- and server-side validation.

This example shows the RequiredFieldValidator validation control that is associated with the text box textFirstname. All validator controls have in common the properties ErrorMessage and ControlToValidate. If the input is not correct, ErrorMessage defines the message that is displayed. The error message by default is displayed at the place where the validator control is positioned. The property ControlToValidate defines the control where the input is checked.

 <asp:TextBox  Runat="server"></asp:TextBox> <asp:RequiredFieldValidator  Runat="server" ErrorMessage="Enter your firstname" ControlToValidate="textFirstname"> </asp:RequiredFieldValidator> 

The following table lists and describes all the validation controls.

Control

Description

RequiredFieldValidator

The RequiredFieldValidator defines that input is required with the control that is validated. If the control to validate has some initial value set, and the user has to change the initial value, you can set this initial value with the InitialValue property of the validator control.

RangeValidator

With the RangeValidator control you can define a minimum and maximum value that the user is allowed to enter. The specific properties of the control are MinimumValue and MaximumValue.

RegularExpressionValidator

With the ValidationExpression property a regular expression using Perl 5 syntax can be set to check the user input.

CompareValidator

For comparing multiple values (such as passwords), the CompareValidator can be used. Not only does this validator support comparing two values for equality, but there are also more options that can be set with the Operator property. the Operator property is of type ValidationCompareOperator that defines enumeration values such as Equal, NotEqual, GreaterThan, and DataTypeCheck. Using DataTypeCheck, the input value can be compared if it is of a specific data type, for example to see if it is a correct date input.

CustomValidator

If the other validator controls don't fulfill the requirements of the validation, the CustomValidator can be used. With the CustomValidator both a client- and server-side validation function can be defined.

ValidationSummary

With the ValidationSummary control, it is easy to write a summary for a page instead of writing error messages directly to the input controls.

With the sample application that you've done until now, the user can input firstname, lastname, and email address. In the following Try It Out the application will be extended by using validation controls.

Try It Out – Check for Required Input and Email Address

image from book
  1. Open the previously created project EventRegistrationWeb with Visual Studio 2005.

  2. Open the file default.aspx.

  3. Add a new column to the table by selecting the right column in the design view of the editor, and by choosing the menu Layout Insert Column to the Right.

  4. First name, last name, and e-mail address are required inputs. A check is done to determine if the e-mail address has the correct syntax. Add three RequiredFieldValidator controls and one RegularExpressionValidator control, as shown in Figure 18-9.

    image from book
    Figure 18-9

  5. Configure the validation controls as defined in this table.

    Validation Control

    Property

    Value

    RequiredFieldValidator1

    ErrorMessage

    Firstname is required.

    ControlToValidate

    textFirstname

    RequiredFieldValidator2

    ErrorMessage

    Lastname is required.

    ControlToValidate

    textLastname

    RequiredFieldValidator3

    ErrorMessage

    Email is required.

    ControlToValidate

    textEmail

    RegularExpressionValidator1

    ErrorMessage

    Enter a valid email.

    ControlToValidate

    textEmail

    ValidationExpression

    \w+([-+.']\w+)*@\w+ ([-.]\w+)*\.\w+ ([-.]\w+)*

    Display

    Dynamic

  6. It is not necessary to enter the regular expression manually. Instead, you can click the ellipsis button of the ValidationEpression property in the property window to start the Regular Expression Editor, as shown in Figure 18-10. This editor makes some predefined regular expressions available where you can select the regular expression to check for an Internet E-Mail Address.

    image from book
    Figure 18-10

  7. If a postback is done to a page that is different from the page that includes the validator controls (using the PostBackUrl property that was set earlier), in the new page you must verify that the result of the previous page was valid, using the IsValid property. Add this code to the Page_Load method of the ResultPage_aspx class:

    protected void Page_Load(object sender, EventArgs e) {    try    { if (!PreviousPage.IsValid) { labelResult.Text = "Error in previous page"; return; } //... 
  8. Now you can start the application. When data is not entered or not correctly written, the validator controls show error messages, as you can see in Figure 18-11.

    image from book
    Figure 18-11

How It Works

The validator controls create both client-side JavaScript code to verify the input on the client and server- side code to validate the input on the server. It is also possible to turn JavaScript off by setting the validator property EnableClientScript to false. Instead of changing the property with every validator control, you can also turn off JavaScript by setting the property ClientTarget of the Page class.

Depending on the client type, the ASP.NET controls return JavaScript to the client or not. This behavior depends on the ClientTarget property. By default, the ClientTarget is set to "automatic", where, depending on the Web browser's functionality, scripting code is returned or not. If the ClientTarget is set to "downlevel", scripting code is not returned for any clients, while setting the ClientTarget property to "uplevel" always returns scripting code.

Setting the property ClientTarget can be done inside the Page_Load() method of the Page class:

 protected void Page_Load(object sender, EventArgs e) { ClientTarget = "downlevel"; } 
image from book




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net