如何验证日期不是.net c中的未来日期#

时间:2011-05-26 04:05:45

标签: c# .net asp.net datetime

只是徘徊,如何验证日期不是.net c#中的未来日期。

示例:

我已在那里应用了验证以进行必要的字段验证。但不知何故,我不知道如何应用验证来检查开始日期,以确保它不是未来的日期(日期不大于当前日期)?

  <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>

比我写下面的代码试用了日期验证。日期验证对我来说似乎不起作用:(

    <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> 
代码背后的代码:

   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);
   }

3 个答案:

答案 0 :(得分:23)

DateTime实现IComparer接口。检查它是否大于DateTime.Now

没有理由解析它,只是这样做:

if(datetime1>datetime2)
{
    ....
}

答案 1 :(得分:3)

我认为您收到的错误是:DateTime.Parse("1000/12/28")而是尝试DateTime.MinValue。您也可以选择使用compareValidators ..

此外,任何理由你不只是[你的约会]&lt; DateTime.now?

答案 2 :(得分:1)

以下是我的代码,该代码在客户端上验证未来的日期值:

ASPX代码:

<tr>
  <td align="right">
    Start Date:
  </td>
  <td>
    <asp:TextBox runat="server" ID="txtActiveDate" size="8"/>(YYYY-MM-DD)
    <!-- Validate if the entered date value is valid -->
    <asp:CompareValidator ID="cvIsActiveDateValid" runat="server"
     ControlToValidate="txtActiveDate"
     ErrorMessage="Invalid Start Date"
     Operator="DataTypeCheck" 
     Type="Date"></asp:CompareValidator>         
    <!-- Validate if the entered value is not future dated -->
    <asp:CompareValidator ID="cvIsActiveDateNotInFuture" runat="server" 
    ControlToValidate="txtActiveDate" 
    ErrorMessage="Start Date cannot be a future date." 
    Operator="LessThanEqual" 
    Type="Date"></asp:CompareValidator>
  </td>
</tr>

ASPX.CS代码:

protected void Page_Load(object sender, EventArgs e)
{
  SetTodaysDateToCompareValidators();
  ...
}

protected void SetTodaysDateToCompareValidators()
{
  string defaultDateFormat = "YYYY-MM-DD";
  string today = DateTime.Today.ToString(defaultDateFormat);
  cvActiveDate.ValueToCompare = today; 
}