ASP.NET 2.0 CompareValidator - Compare Dates through custom user controls

“Hocus Focus” some magic spells … ok, my English is bad

 

I will like to share with you on what I find out on this. If you already know what ASP.NET 2.0 CompareValdator control is, just ignore the top part and read the bottom part. I hope it will help people.

 

ASP.NET 2.0 CompareValidator is quite a common control used by developers to validate input controls. I think the most common scenario is date comparisons. Assuming you have 2 text boxes, one start date and the other one end date. How do you check whether the end date more than the start dates?

 

You can achieve very easily without any extra tweaking like below:

 

<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator" Operator="GreaterThan"

            Type="Date" ControlToCompare="txtStartDate" ControlToValidate="txtEndDate"></asp:CompareValidator>

 

There are a few key areas here that you need to take note on.

 

Attribute

Description

ErrorMessage

Your error description if there is an error triggered

Operator

There are a few types, equal, greaterthan, greater than and equal, datatypecheck

Type

Date, String (for my case I will choose Date)

ControlToCompare

Since I am comparing the end date greater than the start date, so ControlToValidate=EndDate and ControlToCompare=StartDate

ControlToValidate

 

In order to use ControlToCompare and ControlToValidate property, your input controls must be within the web form itself.

 

Now I have a new scenario. Assuming this:

 

You have user controls. 1 is for Start Date and 1 is for End Date. Within the user control, there are 1 text box and a button (which triggers a javascript calendar; pass the values to the textbox).

Drag these 2 user controls into a web form (default.aspx).

 

Try with the code above. Of course you won’t get it work, since there are no longer text boxes in the same form, but user controls instead. The question is how do you pass to ControlToCompare and ControlToValidate?

 

I had tried a lot of ways, like creating properties, played with ValidatationPageAttribute (something like that), passing ClientID, passing ID … just can’t work.

 

Then I found out a way. Try this in your page_load, and it will work J

 

    protected void Page_Load(object sender, EventArgs e)

    {       

        // Take note, passing UniqueID is very important

        // Not ClientID or ID, it won't work

        CompareValidator1.ControlToValidate = uclDate1.FindControl("txtEndDate").UniqueID;

        CompareValidator1.ControlToCompare = uclDate.FindControl("txtStartDate").UniqueID;           

    }   

 

You have to pass in the UniqueID and not others. Very important here.

 

I had placed the source code as below for your personal understanding. I do not have access to sgdotnet site to upload files L

 

// Default.aspx //

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<%@ Register Src="Date2.ascx" TagName="Date2" TagPrefix="uc2" %>

<%@ Register Src="Date1.ascx" TagName="Date1" TagPrefix="uc1" %>

<!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>Testing Compare Validators with User Controls</title>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <uc1:Date1 ID="uclDate" runat="server"></uc1:Date1>

            <br />

            <br />

            <br />

            <uc2:Date2 ID="uclDate1" runat="server" />

            <br />

            <br />

            &nbsp;

            <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator"

                Operator="GreaterThan" Type="Date" ControlToCompare="txtStartDate" ControlToValidate="txtEndDate"></asp:CompareValidator>

            <asp:Button ID="Button1" runat="server" Text="Button" /></div>

    </form>

</body>

</html>

 

// Default.aspx.cs //

 

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {       

        // Take note, passing UniqueID is very important

        // Not ClientID or ID, it won't work

        CompareValidator1.ControlToValidate = uclDate1.FindControl("txtEndDate").UniqueID;

        CompareValidator1.ControlToCompare = uclDate.FindControl("txtStartDate").UniqueID;           

    }   

}

 

// Date1.ascx //

 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Date1.ascx.cs" Inherits="Date1" %>

Start Date <asp:TextBox id="txtStartDate" runat="server"></asp:TextBox>

 

// Date2.ascx //

 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Date2.ascx.cs" Inherits="Date2" %>

End Date <asp:TextBox id="txtEndDate" runat="server"></asp:TextBox>

 

Note: There is still one problem about CompareValidator. Take note, when you specify the type as Date, it actually checks for dd/mm/yyyy. If your textbox display as dd-MMM-yyyy or 10-October-2006, it won’t validate. I had checked online and it seemed that you had to build your own custom validator for this. If anyone knows how I can achieve this in CompareValidator, let me know yeah J

 

Thanks.

Published Monday, October 30, 2006 10:11 AM by chuawenching

Comments

# re: ASP.NET 2.0 CompareValidator - Compare Dates through custom user controls

Tuesday, October 31, 2006 1:06 PM by alvinz_c

Good discovery, bro. Addition to Wen Ching, here is the explaination why the UniqueID works in that scenario.

The reason is, the User Control (ascx) implements the INamingContainer interface, which would assign an unique ID for its child control in the container control (User Control). Normally the format of the ID is <UserControlID>$<ChildControlID>.

UniqueID attribute is fully-qualified string that according to the the ID assigned by the container control, whereas the ClientID property is mostly used for only client-side operation, JavaSCript, for example. ID property will only contain the ID for the control itself. It can explain why the UniqueID property works in that case.

UniqueID - <UserControlID>$<ChildControlID>

ClientID - <UserControlID>_<ChildControlID>

ID - <ChildControlID>

Hope this helps...

Regards,

Alvin Chooi

Microsoft ASP.NET Enthusiast

http://alvinzc.blogspot.com

# re: ASP.NET 2.0 CompareValidator - Compare Dates through custom user controls

Tuesday, October 31, 2006 1:11 PM by alvinz_c

For better practice, assign it once instead of every postback.

protected void Page_Load(object sender, EventArgs e)

{  

  if(!IsPostBack)

  {    

   CompareValidator1.ControlToValidate = uclDate1.FindControl("txtEndDate").UniqueID;

   CompareValidator1.ControlToCompare = uclDate.FindControl("txtStartDate").UniqueID;            

  }

}  

Nice Work, bro!

Regards,

Alvin Chooi

Microsoft ASP.NET Enthusiast

http://alvinzc.blogspot.com

# re: ASP.NET 2.0 CompareValidator - Compare Dates through custom user controls

Tuesday, October 31, 2006 1:34 PM by alvinz_c

Regarding the date format validation of CompareValidator. If I am not mistaken, it would only validate the dd/MM/yyyy, dd-MM-yyyy and dd/MM/yy, dd-MM-yy.

Of course, you can ask "him" to validate another format of date - MM/dd/yyyy...... by specifying the CultureInfo in the page, either programmatically or declaractively. "en-GB" is used for dd/MM/yyyy and "en-US" is usef for MM/dd/yyyy. For instance,

System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB")

or

<@Page CultureInfo="en-GB" ....>

Regards,

Alvin Chooi

Microsoft ASP.NET Enthusiast

http://alvinzc.blogspot.com

# re: ASP.NET 2.0 CompareValidator - Compare Dates through custom user controls

Tuesday, October 31, 2006 2:05 PM by chuawenching

Hey, thanks for the explanations. Ya, I am aware of the CultureInfo, but I did not dare to implement it in this project until I get some approval from my Project Lead.

# ASP.NET 2.0 CompareValidator Part 2 - ControlToValidate/ControlToCompare do not work in MasterPage

Saturday, November 04, 2006 1:44 PM by Wen Ching's Blog

This is a part 2 of the earlier one. Why there is a part 2? You will know it soon. Before you read this,