Search code examples
asp.netupdatepanelrequiredfieldvalidator

Unable to enable/disable validator in control embedded in UpdatePanel


Arg. Inheriting projects is SO much fun. Especially when they don't work well, and even more especially when they contain UpdatePanels...

I have a shipping address user control inside an UpdatePanel. We need to be able to process international addresses, so one thing I've done is show/hide the State dropdown depending on if the country selected is US or not. In addition, I have a RequiredFieldValidator on that dropdown.

When the user control is used on a normal page elsewhere in the application, everything is great. However, in the UpdatePanel, .NET is not seeing the RFV even though JavaScript does.

Address.ascx: (snipped)

    <li class="form-list-question question-state">
        <span class="form-label">
          <asp:Label ID="lblState" runat="server" SkinID="FieldLabel" AssociatedControlID="ddlState" Text="State" /></span>
        <asp:DropDownList ID="ddlState" runat="server" SkinID="State" DataSourceID="dsStates" AppendDataBoundItems="true" ViewStateMode="Enabled"
        DataTextField="Name" DataValueField="Abbr" CssClass="required">
            <asp:ListItem Text="" Value=""></asp:ListItem>
        </asp:DropDownList>
        <asp:RequiredFieldValidator ID="rfvState" runat="server" EnableClientScript="true" Display="None" ControlToValidate="ddlState"
        ErrorMessage="State is required." ValidationGroup="Address" />
    </li>

address.js: (snipped)

        function SetFormByCountry() {
    if (isUsTerritory()) {
        $('.question-state').show();
        if ($('#rfvState').length > 0) {
            $('#rfvState').enabled = true;
        }
    } else {
        $('.question-state').hide();
        if ($('#rfvState').length > 0) {
            $('#rfvState').enabled = false;
        }
    }
}

Current behavior: When a country other than the US is selected, the State dropdown disappears as appropriate, but when the form is submitted, validation still occurs on the now hidden dropdown. There are no JS errors created.

Expected behavior: Given the above scenario, the RequiredFieldValidator should be disabled and the form should post.


Solution

  • Have you tried using the ValidatorEnable function?

    It's an ASP.Net javascript function that can be used to turn off client side validators; in your example, you should be able to do the following in your client side javascript (where you set the enabled property):

    ValidatorEnable(document.getElementById('<%=rfvState.ClientID%>'), false);
    

    My only other suggestion is to fire a async postback when the country is changed and remove the state validator server side.