views:

32

answers:

1

I’ve got a webform with two custom validators; one to validate a string is of date format (I don’t care what format, so long as it can convert), and another to ensure that one date is equal to or greater than another (just couldn’t get the compare validator to play nice with any date format). Here’s how it looks:

<asp:TextBox ID="txtResourceStartDate" runat="server" CssClass="textBox mandatory dateField" />
<asp:CustomValidator ID="valResourceStartDateIsDate" runat="server" ControlToValidate="txtResourceStartDate" Display="None" ErrorMessage="Start date must be a valid date" OnServerValidate="Date_ServerValidate" />

<asp:TextBox ID="txtResourceEndDate" runat="server" CssClass="textBox mandatory dateField" />
<asp:CustomValidator ID="valResourceEndDateIsDate" runat="server" ControlToValidate="txtResourceEndDate" Display="None" ErrorMessage="End date must be a valid date" OnServerValidate="Date_ServerValidate" />

<asp:CustomValidator Display="None" Text="" ID="valForStartEndDate" runat="server"         OnServerValidate="ValidateStartEndDate" ErrorMessage="Last day must be greater than or equal to first day" />

And code wise:

protected void Date_ServerValidate(object source, ServerValidateEventArgs args)
{
  DateTime outDate;
  args.IsValid = DateTime.TryParse(args.Value, out outDate);
}

protected void ValidateStartEndDate(object sender, ServerValidateEventArgs e)
{
  e.IsValid = DateTime.Parse(txtResourceEndDate.Text) >= DateTime.Parse(txtResourceStartDate.Text);
}

The problem I have is that the ValidateStartEndDate validator is firing before the Date_ServerValidate validator so if the date is not valid a format exception is thrown on DateTime.Parse. Obviously this validator could check for a valid date before parsing but I’d really prefer to have a discrete validator with an appropriate message.

So the question is this; what is determining the sequence with which the validators fire? Unless I’m missing something, this is not declared at the tag level. Thanks!

A: 

You can't count on a certain sequence the validators will fire and also you shouldnt. You have to make sure for yourself that the order is irrelevant.

So you could

  1. check for the valid date simultaneously with the Equal-Greater-Check.
  2. First Call your IsDate-Validator's Validate()-Function and then check if it IsValid
  3. All validators are added to the Page.Validators collection and validation runs through this collection in order. If your logic really should rely on this order: change the order of the validators in the ASPX-Page

Some interesting infos about Page-Validation: http://msdn.microsoft.com/en-us/library/aa479045.aspx

Tim Schmelter
Thanks Tim, I've gone with option 2 and accepted your answer. Having said that, I'm still unsure as to what determines the sequence. It's NOT the order they're declared on the page or I wouldn't have this problem. Still, it works now so curiosity aside, I'm happy. Thanks!
Troy Hunt