Search code examples
c#asp.netpropertiesrequiredfieldvalidator

Setting ValidationGroup on RequiredFieldValidator from a property isn't setting correctly


I am trying to set my required field validators ValidationGroup dynamically from a property on my page however they are not firing. If I set the string manually it fires. My assumption is that its not pulling the property properly into the ValidationGroup. Am I missing something?

<asp:RequiredFieldValidator runat="server" ID="rfvHouseName" ControlToValidate="txtHouseName" ErrorMessage="Please enter a house name/no." ForeColor="Red" ValidationGroup="<%#ValidationGroup%>"><i class="fa fa-star requiredFieldStar"></i></asp:RequiredFieldValidator>
<asp:TextBox ID="txtHouseName" runat="server" MaxLength="50" CssClass="form-control" />

private static string _validationGroup = "NewAddress";

public virtual string ValidationGroup
{
    get { return _validationGroup; }
    set { _validationGroup = value; }        
}

Solution

  • You have to set it in code behind

    rfvHouseName.ValidationGroup = ValidationGroup;
    

    Or if you really want to use it inline, you have to use it like this

    <asp:RequiredFieldValidator ValidationGroup='<%# ValidationGroup %>'
    

    However for the second one to work you have to call DataBind() from code behind every time.

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