Search code examples
c#asp.netrequiredfieldvalidator

Set Required Field Validator from .ASPX page


I am trying to set the enable attribute on a required field validator control from a function in my code behind. The below code seems to not be working. What am I missing? I am doing this so I can test my code behind validation and not have to go to all required field validator controls to change the enable property to false etc.

            <asp:RequiredFieldValidator ID="rfvRadTxtTimerName" 
                runat="server" ForeColor="Red"
                ControlToValidate="txtTimerName"
                ErrorMessage="* Email Address is a required field."
                ValidationGroup="submitTimer"
                Enabled=<%# (EnableOrDisableRequiredValidators() == true ? true : false) %>
                Display="Dynamic" >
            </asp:RequiredFieldValidator>


    protected bool EnableOrDisableRequiredValidators()
    {
        return false;
    }

Solution

  • <asp:RequiredFieldValidator ID="rfvRadTxtTimerName" 
        runat="server" ForeColor="Red"
        ControlToValidate="txtTimerName"
        ErrorMessage="* Email Address is a required field."
        ValidationGroup="submitTimer"
        Display="Dynamic">
    </asp:RequiredFieldValidator>
    

    Meanwhile somewhere in code behind:

    rfvRadTxtTimerName.Enabled = false // true? 
    

    I'm not 100% sure, but I think it has to do with data binding and when controls values are initialized.

    As an aside, this line (if you found a way to make it work)

    Enabled=<%# (EnableOrDisableRequiredValidators() == true ? true : false) %>
    

    could be cleaned up

    Enabled=<%# EnableOrDisableRequiredValidators() %>