Search code examples
asp.netvalidationasp.net-validators

ASP.NET Validator with dynamic error text


I need some dynamic text in my validator ErrorMessage.

This is what I'm trying to do, but it doesn't work:

<td>
  <asp:TextBox runat="server" ID="tbIncome_A_3" MaxLength="12"></asp:TextBox>
  <asp:CompareValidator ID="comvIncome_A_3" runat="server" ControlToValidate="tbIncome_A_3" Display="Dynamic" Operator="DataTypeCheck" Type="Currency"
    ErrorMessage="*Value entered for <%=DateTime.Today.Year - 3 %> Income must be a dollar value.">
    <span class="alert">*</span>
  </asp:CompareValidator>
</td>
...
<div>
  <asp:ValidationSummary ID="vs" runat="server" CssClass="alert alert-danger alert-dismissible" HeaderText="This page has been saved, but it's not complete." ForeColor="" EnableClientScript="false" EnableViewState="false" />
</div>

I expect <%=DateTime.Today.Year - 3 %> to render as '2014' in the ValidationSummary, but it instead renders as plaintext. I feel like I'm missing something very trivial to make this work.


Solution

  • It can be done like this:

    ErrorMessage='<%# "*Value entered for " + DateTime.Today.AddYears(-3).Year + " Income must be a dollar" %>'
    

    However you will need to call DataBind(); in the Page_Load of your page. So since you do need to modify the code behind anyway, why not set the error message from there... (DataBind() not needed then)

    tbIncome_A_3.ErrorMessage = "*Value entered for " + DateTime.Today.AddYears(-3).Year + " Income must be a dollar";