Dawson
Dawson

Reputation: 573

Disabling RequiredFieldValidator for hidden fields

I have a dropdownlist that should be mandatory when not hidden, so i have a RequiredFieldValidator for this.

<table runat="server" id="tblLocations" class="ts1">
    <tr>
        <td class="tr0">
            Location:
        </td>
        <td>
            <asp:DropDownList ID="ddlLocations" runat="server">
            </asp:DropDownList>
            <asp:RequiredFieldValidator ID="rfvDdlLocations" runat="server" ControlToValidate="ddlLocations" InitialValue="0" validationgroup="LocationValidation"  ErrorMessage="Please select a Location" />
        </td>
    </tr>
</table>

When a radio button is selected I set the visibility of this table to false.

I want to disable validation of this field when not visible so I set this on the radio button changed event:

rfvDdlLocations.Enabled = tblLocations.Visible;

This doesn't disable the verification however.

I have tried using JQuery as suggested elsewhere but this has no effect either:

<script type="text/javascript">
$("[id$='btnDelegate']").click(function () {
    if (!$("[id$='tblLocations']").is(':visible')) {
        ValidatorEnable($("[id$='rfvDdlLocations']")[0], false);
    }
    //ValidationSummaryOnSubmit("LoginUserValidationGroup");
    if (Page_ClientValidate("LocationValidation")) {
        alert('it is valid');
        return true;
    }
    else {
        alert('Not valid');
        return false;
    }
});

Upvotes: 1

Views: 423

Answers (1)

Sherif Ahmed
Sherif Ahmed

Reputation: 1946

you should use a customvalidator in this case as below

<asp:CustomValidator ID="cvDdlLocations" runat="server" ControlToValidate="ddlLocations" ValidationGroup="LocationValidation"  ErrorMessage="Please select a Location" OnServerValidate="cvDdlLocations_ServerValidate" ClientValidationFunction="validateLocation" />

and for client validation

function validateLocation(s, args) {
    if($('#'<%= Radio.ClientID %>).is(':checked')){
        args.IsValid = true;
    }
    else {
        args.IsValid = $('#<%= ddlLocations.ClientID%>').val() != "0";
    }
}

and for server validation

protected void cvPrice2Edit_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = true;
    if(!Radio.Checked) {
        args.IsValid = ddlLocations.SelectedValue != "0";
    }
}

I hope this helps

Upvotes: 1

Related Questions