Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate the date is not the future date in .net c#

Just wandering, how can I validate the date is not the future date in .net c#.

Example:

I have applied a validation there for required field validation. But somehow I have no idea how to apply the validation to check the start date to make sure it's not the future date (date not greater then the current date)?

  <tr>
        <td align="right">Start Date:</td>
        <td><asp:TextBox runat="server" ID="activeDate" size="8"/>(YYYY-MM-DD)
            <asp:RequiredFieldValidator ID="reqvactiveDate" runat="server"
                 ControlToValidate="activeDate" Display="Dynamic" EnableClientScript="true"
                 ErrorMessage="required" />

        </td>
    </tr>

than I wrote the following code to tried out the date validation. The date validation doesn't seem working for me :(

    <tr>
        <td align="right">Start Date:</td>
        <td><asp:TextBox runat="server" ID="activeDate" size="8"/>(YYYY-MM-DD)
            <asp:RequiredFieldValidator ID="reqvactiveDate" runat="server"
                 ControlToValidate="activeDate" Display="Dynamic" EnableClientScript="true"
                 ErrorMessage="required" />

            <asp:CustomValidator runat="server"
                ID="valDateRange" 
                ControlToValidate="activeDate"
                onservervalidate="valDateRange_ServerValidate" 
                ErrorMessage="enter valid date" />
        </td>
    </tr> 

code behind:

   protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
   {
       DateTime minDate = DateTime.Parse("1000/12/28");
       DateTime maxDate = DateTime.Parse("2011/05/26");
       DateTime dt;

       args.IsValid = (DateTime.TryParse(args.Value, out dt)
                       && dt <= maxDate
                       && dt >= minDate);
   }
like image 488
Jin Yong Avatar asked Nov 27 '22 18:11

Jin Yong


1 Answers

DateTime implements an IComparer interface. Check if its greater than DateTime.Now

There is no reason to parse it, just do:

if(datetime1>datetime2)
{
    ....
}
like image 67
soandos Avatar answered Feb 16 '23 09:02

soandos