Showing posts with label validation. Show all posts
Showing posts with label validation. Show all posts

Using the RequiredFieldValidator attribute InitialValue to control valid selections in your DropDownLists

Posted on: Monday, 19 October 2009 18:00

The RequiredFieldValidator is a common utility in the asp.net coders validation toolkit. Its simple to use and probably represents one of the most common requirements for validation - that data must be there.

Its official definition is:

Evaluates the value of an input control to ensure that the user enters a value.

Using it to require TextBox content is an obvious and straightforward use but using it to validate DropDownList selections might not occur to you straight away.

How would you stop the user from submitting the form with "Please select" selected in the sample DropDownList below?

<asp:DropDownList ID="DropDownList1" runat="server" ValidationGroup="DropDownSample">
   <asp:ListItem>Please select</asp:ListItem>
   <asp:ListItem>Lincolnshire</asp:ListItem>
   <asp:ListItem>Nottinghamshire</asp:ListItem>
</asp:DropDownList>

InitialValue is the key. To use it you simply setup your RequiredFieldValidator as you normally would but add in the extra InitialValue attribute set to the string of text that you don't want to be submitted.

The RequiredFieldValidator for the DropDownList above would look something like this:

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" InitialValue="Please select" ControlToValidate="DropDownList1" ErrorMessage="Please select a shire" />

A Real World Databound Example

The technique above is great for ensuring that your users properly select values for your DropDownLists. In the real world however you'll usually find yourself needing to bind the data to your drop down. So the issue becomes how do you combine your initial value text with the data that's bound?

There is an attribute called AppendDataBoundItems="True" which you can add to a DropDownList. This means that when you databind your dropdown the options you have hard coded in will not be overwritten.

So if you added the first starter ListItem with the text of "Please select" and databind your DropDownList it will be preserved at the top with your data below. This means you don't have to do any special tricks to get your default text included in your data set.

In the sample below I have included a datasource which randomly generates a list of numbers. Its a good example of how to create your own bindable data objects, but its not the focus of this article.

<asp:DropDownList ID="DropDownList2" runat="server" ValidationGroup="DataBoundDropDownSample"
    AppendDataBoundItems="True" DataSourceID="ObjectDataSource1">
    <asp:ListItem>Please select</asp:ListItem>
</asp:DropDownList>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    SelectMethod="Select" TypeName="RunTingsProper.Sample.Data.SimpleIntegerData">
</asp:ObjectDataSource>
<div>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" InitialValue="Please select"
        ControlToValidate="DropDownList2" ValidationGroup="DataBoundDropDownSample" ErrorMessage="Please select a number" /></div>
<asp:Button ID="Button2" runat="server" Text="Select" ValidationGroup="DataBoundDropDownSample" />

Download these examples

You can download these examples to play around with here:

Bonus tip - InitialValue can also be used for TextBox's

The text that you set in the InitialValue can also be used on other input controls. In theory you can use it to prevent any value that you like being entered into a TextBox. The TextBox doesn't have to have that value embedded at the start - it just can't be submitted with that value.

In practice this doesn't really come in useful very often; usually if you do need this kind of feature you can solve your problem more succinctly with a RegularExpressionValidator.

Bonus tip #2 - You can use more than one validator on a control

Don't forget that you can add more than one RequiredFieldValidator to work on a single control. This means that should you find yourself wanting to prevent more than one selection in a DropDownList you could wire up as many RequiredFieldValidators (each with their own InitialValue attributes) as you need to solve the problem.

Further Reading

kick it on DotNetKicks.com Shout it

Using a CompareValidator to check input is a valid date

Posted on: Tuesday, 28 July 2009 23:27

The CompareValidator can do more than just compare two controls. You can also compare it against several of the main .net data types such as Date, Integer, Double and Currency.

To do this you would set Operator="DataTypeCheck" and instead of setting the ControlToCompare or ValueToCompare attributes as you normally would you use the Type="Date" (or any of the data types I have listed above).

Here is an example page which illustrates a very simple usage of it:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CompareValidatorExample._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>CompareValidator Date Validation</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            CompareValidator Date Validation</h1>
        <asp:TextBox ID="TextBox1" ValidationGroup="CompareValidatorDateTest" runat="server"></asp:TextBox>
        <asp:Button ID="ButtonSubmit" runat="server" ValidationGroup="CompareValidatorDateTest" Text="Validate Date" /><br />
        <asp:CompareValidator ID="CompareValidator1" Display="dynamic" ControlToValidate="TextBox1"
            Type="Date" Operator="DataTypeCheck" Text="Please enter a valid date" runat="server"
            ValidationGroup="CompareValidatorDateTest" />
    </div>
    </form>
</body>
</html>

The ValidationGroup attribute

Here is another little side-tip; the ValidationGroup attribute that I have spread throughout this code is a great way to avoid confusion later on when you end up with more than one group of form items in a page. If for example you have a login box in the top corner of your page then the ValidationGroup attribute will let you stop the "username required" validator firing when you click the Submit button on this example.

Advanced Validation

The CompareValidator is one of those controls that provides great basic features but quickly runs out of steam when your websites require a little bit more customisation.

Two things to watch out for when using the CompareValidator in this way is that the Date type will take the format of whatever locale the server is running in. As a UK developer I have sometimes found the server running in an American locale when I uploaded the site which flipped the month and day around.

Another caveat is currency validation - no currency symbols allowed!

To get around these limitations you have the option of using regular expressions via the RegularExpressionValidator or going all-out and developing your own validators by inheriting the base class BaseValidator.

Further Reading