ValueToCompare属性无法转换为类型“日期”错误

时间:2017-10-08 12:37:32

标签: c# asp.net validation

我有一个链接到文本框的比较验证器:

<asp:TextBox runat="server" ID="Birthdate" CssClass="form-control" TextMode="Date"/>

<asp:CompareValidator ID="cmpBDate" runat="server" ErrorMessage="Must be at least 20 years old" 
ControlToValidate="Birthdate" Type="Date" ValueToCompare="<%# DateTime.Today.AddYears(-20).ToShortDateString() %>" 
Operator="LessThan" CssClass="text-danger"  Display="Dynamic">
</asp:CompareValidator>

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

但是我收到了一个错误:

  

'cmpBDate'的ValueToCompare属性的值“”不能   转换为“日期”类型。

堆栈跟踪:

[HttpException (0x80004005): The value '08-Oct-97' of the ValueToCompare property of 'cmpBDate' cannot be converted to type 'Date'.]
System.Web.UI.WebControls.CompareValidator.ControlPropertiesValid() +2619109
System.Web.UI.WebControls.BaseValidator.OnPreRender(EventArgs e) +37
System.Web.UI.Control.PreRenderRecursiveInternal() +88
System.Web.UI.Control.PreRenderRecursiveInternal() +160
System.Web.UI.Control.PreRenderRecursiveInternal() +160
System.Web.UI.Control.PreRenderRecursiveInternal() +160
System.Web.UI.Control.PreRenderRecursiveInternal() +160
System.Web.UI.Page.ProcessRequestMain(Boolean 
includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint) +985

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试根据已知的服务器端格式化日期。我猜2917-10-08的内容应该有效。也许往返变体会起作用。