Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

C# CustomValidator for valid DateTime

Hi Guys

I wasted quite a bit of time on this, so hopefully it will assist someone else:

Add a custom validator and on the properties window just set the ID and ControlToValidate

Then double click and add:

Code
Boolean valid = new Boolean();
  args.IsValid = ValidateDateTime(valid, source);

Now we need to write the ValidateDateTime function

Code
protected Boolean ValidateDateTime(Boolean valid, object source)
    {

  DateTime VerifyDate;
  CustomValidator current = (CustomValidator)source;
  TextBox TempControl = (TextBox)FindControl(current.ControlToValidate);

  valid = false;

  try
  {
    VerifyDate = DateTime.Parse(TempControl.Text);
  }
  catch (Exception ex)
  {
    current.ErrorMessage = "Please enter a valid date/time";
    return false;
  }

  if (VerifyDate < DateTime.Today)
  {
    current.ErrorMessage = "The date cannot be in the past";
    return false;
  }

  return true;

    }

This will work as long as you are validating a textbox. The ID of the validator as well as the textbox is dynamically calculated (from source and source.ControlToValidate so there is no need to alter it to make it work :) )

BTW: Here is the markup for an actual custom validator (which uses the above code)

Code
<asp:CustomValidator ID="ControlID" runat="server"
    ControlToValidate="ControlToCheck" ErrorMessage="Some message"
    onservervalidate="ControlID_ServerValidate"></asp:CustomValidator>

(The onservervalidate event will be added when double clicking on the control)

You can also reuse this code for all the validators on the page.


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C#] by JoseCmanXDIINov 28, 2021 01:12 PM 6 203 Nov 28, 2021 01:12 PM
Last Post: OddEye
[C#] by MeincraftJul 3, 2015 12:18 PM 1 50 Jul 3, 2015 12:18 PM
Last Post: +Haze
[C#] by SIM-1809171Jun 23, 2015 06:49 AM 3 107 Jun 23, 2015 06:49 AM
Last Post: phrootoo