我正在使用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所以,不需要比较值,应该被接受
答案 0 :(得分: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
}
}