禁用隐藏字段

时间:2015-11-11 05:55:04

标签: javascript jquery asp.net validation

我有一个下拉列表,在未隐藏时应该是必需的,所以我有一个RequiredFieldValidator。

<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>

选择单选按钮后,我将此表的可见性设置为false。

我想在不可见时禁用此字段的验证,因此我在单选按钮更改事件上设置了此项:

rfvDdlLocations.Enabled = tblLocations.Visible;

但是,这并不会禁用验证。

我尝试过使用其他地方建议的JQuery,但这也没有效果:

<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;
    }
});

1 个答案:

答案 0 :(得分:1)

在这种情况下你应该使用customvalidator,如下所示

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

并进行客户验证

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

和服务器验证

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

我希望这会有所帮助