Rotem B Rotem B - 17 days ago 6
ASP.NET (C#) Question

asp net RegularExpressionValidator doesn't show message when invalid

I have a very simple scenario:

.ascx:

<div class="record">
<div id="label1" class="label">First name</div>
<div class="value">
<telerik:RadTextBox runat="server" ID="firstName" ClientIDMode="Static" Width="200"></telerik:RadTextBox>
</div>
<div class="validation">
<asp:RegularExpressionValidator ID="firstNameRegularExpresionValidator1" ClientIDMode="Static" runat="server" ControlToValidate="firstName" SetFocusOnError="True" ValidationExpression="<%# NameValidatorProp.FirstName.Regex %>" ErrorMessage="<%# NameValidatorProp.FirstName.ErrorMessage %>" Display="Dynamic" />
</div>
</div>


In the .ascx.cs file I have initialized NameValidatorProp.

The problem is that the validation occured and the regular expression validator is with display:inline when word does not match regex, however, the validation error doesn't. Event when I changed the ErrorMessage to be a const string from code behind. If I enter hard coded ErrorMessage, it works of course.

A workaround is to set on page load the ErrorMessage property to the value I have. It works, but when I have a few more textbox items, its just looks ugly.

Any suggestions why the ErrorMessage never shows the value?

Answer

You have to add DataBind() to the Page_Load when you use that kind of declarative syntax. Read more

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