2013-10-04 58 views
0

我正在使用asp.net的比較驗證器來比較日期,我將輸入日期與今天的日期進行比較,以便我編寫代碼如下。在asp.net Validator中比較日期和異常日期Validator

<asp:CompareValidator ID="StartDateCompareVal" ValidationGroup="vgStep4" runat="server" 
              ControlToValidate="txtDueDate" Display="Dynamic" ErrorMessage="Dateshould be greater than today's date." 
              Operator="GreaterThan" ValueToCompare="<%# DateTime.Today.ToShortDateString() %>" 
              Type="Date"></asp:CompareValidator> 

它工作正常,但現在,我的要求是,如果有人進入日期00/00/0000所以,沒有必要比較值的,應該接受

回答

0

看起來你可能想使用CustomValidator而不是CompareValidator

.aspx頁面中:

<form id="frmAspnet" runat="server"> 
    <asp:ValidationSummary runat="server" ID="vSummary" /> 
    <div> 
     <label> 
      Enter Date Greater Than Today: 
      <asp:TextBox runat="server" ID="txtDate" /> 
     </label> 
    </div> 
    <div> 
     <asp:Button runat="server" ID="cmdSubmit" Text="Submit" /> 
    </div> 
</form> 

後面的代碼:

private void cmdSubmit_Click(object sender, EventArgs e) 
{ 
    String validationGroup = "vgStep4"; 
    vSummary.ValidationGroup = validationGroup; 
    Page.Validate(validationGroup); 

    DateTime dateEntered = DateTime.TryParse(txtDate.Text, out dateEntered) ? dateEntered : DateTime.MinValue; 
    Page.Validators.Add(new CustomValidator() 
    { 
     IsValid = (dateEntered > DateTime.Now.Date) || (txtDate.Text == "00/00/0000"), 
     ValidationGroup = validationGroup, 
     ErrorMessage = "Date should be greater than today's date." 
    }); 

    if (Page.IsValid) 
    { 
     // Date entered is valid! 
     // or 00/00/0000 was entered 
    } 
}