0

我正在使用 asp.net 的比较验证器来比较日期,我正在将输入日期与今天的日期进行比较,因为我编写了如下代码。

<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 所以,不需要比较值,应该被接受

4

1 回答 1

0

看起来您可能想要使用 aCustomValidator而不是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
    }
}
于 2013-10-04T17:04:36.683 回答