Hack Forums
[C#] C# CustomValidator for valid DateTime - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C#] C# CustomValidator for valid DateTime (/showthread.php?tid=815484)



C# CustomValidator for valid DateTime - ShadowCloud - Nov 13, 2010

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.