A simple introduction to ASP.Net validators

October 19, 2008 at 5:04 pm 2 comments

When I first started using validators in ASP.Net, I was confused by the documentation. This article is intended to be a very simple introduction to validators in ASP.Net.

What is a Validator
A validator checks the input of a control to verify that the value falls within criteria you specified. If we create a simple web site with the following code:

A simple Validator
The following is an default.aspx file.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Validator Introduction</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="NumberLabel" runat="server" Text="Number" />
        <asp:TextBox ID="NumberTextBox" runat="server" />
        <asp:Button ID="submitbutton" runat="server" Text="submit" />
    </div>
    </form>
</body>
</html>

All this is a text box with a submit button. It would be nice to make sure that the user enter a valid number. To do this, we’ll add a validator to check that it is a number.

    <div>
        <asp:Label ID="NumberLabel" runat="server" Text="Number" />
        <asp:TextBox ID="NumberTextBox" runat="server" />

        <asp:RangeValidator ID="NumberRangeValidator"
            runat="server" ErrorMessage="Input must be in the range of 1-10"
            ControlToValidate="NumberTextBox" MaximumValue="10" MinimumValue="1"
            Type="Integer" EnableViewState="false" Display="Dynamic">*</asp:RangeValidator>
        <asp:Button ID="submitbutton" runat="server" Text="submit" />
    </div>

The validator we added is a range validator. On this validator, we have set the following:

  • ControlToValidate the ID of the control you are validating.
  • The MininumValue and MaximumValue sets the range you want the input to be in.
  • The Type is set to Integer.
  • ErrorMessage is the error message to be displayed when validation fails
  • Display is set to Dynamic because it will otherwise take up the space of the error message.
  • EnableViewState is set to false since there is no reason to store viewstate for an validator.

When you hit submit and you enter a text value or a value that does not fall into 1-10, a red error text appear next to the control.

The problem is when you enter a blank value and hit submit, no error is display even though a blank value is not in the range 1-10.

Handling blank values

One issue to watch out for is that virtually all of the validators will not validate if the value is set to blank. This is why the range validator failed to catch the blank input even though a blank is not in the range of 1-10.

To get around the problem, we have to use the required validator in conjunction with your value validator. The required validator basically checks that you entered something.

    <div>
        <asp:Label ID="NumberLabel" runat="server" Text="Number" />
        <asp:TextBox ID="NumberTextBox" runat="server" />
        <asp:RangeValidator ID="NumberRangeValidator"
            runat="server" ErrorMessage="Input must be in the range of 1-10"
            ControlToValidate="NumberTextBox" MaximumValue="10" MinimumValue="1"
            Type="Integer" EnableViewState="false" Display="Dynamic">*</asp:RangeValidator>
        <asp:RequiredFieldValidator ID="NumberRequiredValiator" runat="server"
            ControlToValidate="NumberTextBox" ErrorMessage="Number field cannot be blank."
            EnableViewState="false" Display="Dynamic">*</asp:RequiredFieldValidator>
        <asp:Button ID="submitbutton" runat="server" Text="submit" />
    </div>

Now when you enter a blank input, the required validator will prompt the user to enter a value

Using a Validation Summary to group error message together
One problem you’ll notice is that the error message takes up space whether it is displayed or not. We will next get around the issue by creating a validation summary to group all of the error messages in one spot. To mark which field we need to fix, we’ll add a “*” to the field that failed validation.

    <div>
        <asp:ValidationSummary ID="ValidationSummary" runat="server" />
        <asp:Label ID="NumberLabel" runat="server" Text="Number" />
        <asp:TextBox ID="NumberTextBox" runat="server" />
        <asp:RangeValidator ID="NumberRangeValidator"
            runat="server" ErrorMessage="Input must be in the range of 1-10"
            ControlToValidate="NumberTextBox" MaximumValue="10" MinimumValue="1"
            Type="Integer" EnableViewState="false" Display="Dynamic">*</asp:RangeValidator>
        <asp:RequiredFieldValidator ID="NumberRequiredValiator" runat="server"
            ControlToValidate="NumberTextBox" ErrorMessage="Number field cannot be blank."
            EnableViewState="false" Display="Dynamic">*</asp:RequiredFieldValidator>
        <asp:Button ID="submitbutton" runat="server" Text="submit" />
    </div>

Now whenever we get a validation error, all of the validation errors appear in the validation summary area. In addition, a red “*” appears next to the field that requires correction.

Using Validation Group to control what is validated

Starting in ASP.Net 2.0, it becomes possible to control what is validated when you submit. This allows you to have multiple submit button on the same page. When you click on the submit, only part of the page is validated.

The multiple submits are controlled by validation groups. Suppose you have a page that has address and credit card, you can group all of the address validation under the group “address” and the credit card under the group “creditCard”. When you press the check credit card button, only the credit card number field is validated.

Validation group is a field in the controls.

        <asp:TextBox ID="Address" runat="server" ValidationGroup="address" />
        <asp:Button ID="AddressSubmit" runat="server" Text="Submit Address" ValidationGroup="address"/>
        <asp:TextBox ID="creditCardNumber" runat="server" ValidationGroup="creditCard" />
        <asp:Button ID="CCSubmit" runat="server" Text="Submit Credit Card" ValidationGroup="creditCard"/>

In your click event, you can add the code “if (Page.IsValid)” in your click event handler. This will cause a validation on the control in the same validation group that the event handler is attached to. In the above set of controls, pressing CCSubmit will cause validatoin on the creditCardNumber textbox.

Advertisements

Entry filed under: asp.net. Tags: .

Switching to the Open source Athero driver after Mandriva 2009 upgrade Fixing Windows Delayed Write Failed error

2 Comments Add your own

  • 1. Boss Resurfacing  |  September 6, 2009 at 9:18 pm

    Off topic – Help with PM?
    lost password
    Boss Resurfacing
    Boss Resurfacing

    Reply
  • 2. Barbara33  |  October 22, 2009 at 12:18 pm

    However, after hearing a preliminary mix of the record, Berry Gordy was not offended by Gaye’s embrace of countercultural politics, but was bothered by the album’s format, which had each song leading to the next. ,

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

October 2008
M T W T F S S
« Sep   Nov »
 12345
6789101112
13141516171819
20212223242526
2728293031  

Most Recent Posts


%d bloggers like this: