August 25, 2011

RangeValidator is a validation control provided by asp.net. This control can be used to validate a range of string, date, integer and double values. In this post, I will show how to use the RangeValidator to validate a range of date using today’s date as the maximum value.

The following is the RangeValidator markup.

RangeValidator markup
  1. <asp:TextBox ID="T1" runat="server"></asp:TextBox>
  2. <asp:RangeValidator ID="RV1" runat="server" ControlToValidate="T1" Type="Date" MinimumValue="01/01/2000" ErrorMessage="*"></asp:RangeValidator>
  3. <asp:Button ID="Button1" runat="server" Text="Button" />

The TextBox control is added where the users will enter the value. The Button control is added to test validation. The RangeValidator is added – its ControlToValidate property is set to TextBox’s id, data type is set to Date, the minimum value is set to an arbitrary date. The maximum value is set in the Page_Load event as shown below.

Page_Load event
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     RV1.MaximumValue = DateTime.Today.ToShortDateString();
  4. }

The maximum value expects a value of type string, so the string format of today’s date is passed as the MaximumValue.

2 comments:

Anonymous said...

Hi Shahed,

I tried your code, it works good but it won't work inside a update panel. Did you ever came across this bug?

Thanks.

Sylvain

Shahed Kazi said...

Hi, As you can see, code is running from Page_Load event. Make sure whatever script you write for the update panel, calls that script.

Reference: Shahed Kazi at AspNetify.com