如何隐藏asp自定义验证器的错误消息

时间:2013-10-08 19:38:23

标签: c# asp.net

我正在使用asp requiredfieldvalidator。我希望只有在选中表单上的复选框时才会触发必填字段验证器。

当复选框被触发时,验证器按预期工作并显示错误消息,但是当取消选中该复选框时,显示的错误消息将保留在屏幕上。我尝试了不同的选项,如validator.resetForm();禁用验证器,隐藏验证器但错误消息保留在屏幕表单上。这是我的代码的简化版本:

<script src="jquery-1.4.2.min.js"></script>
<!DOCTYPE html>
<script type="text/javascript">
    function enableDisableControls(value) {
      var enabledSilentPost = $("#<%=chkEnableSilentPost.ClientID%>").attr("checked");
      var validatorControl = $("#<%=valApprovalURL.ClientID%>")[0];

      ValidatorEnable(validatorControl, enabledSilentPost);

      // If the checkbox is false then assume that the 
      if (!enabledSilentPost) {
        validatorControl.enabled = false;
      }
    }

$(document).ready(function () {
  $("#<%=chkEnableSilentPost.ClientID%>").click(function () {
    enableDisableControls();
  });

  enableDisableControls();
});

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
  <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
  <div>
    <asp:CheckBox ID="chkEnableSilentPost" runat="server" Width="250px" Text="Enable" />
    <asp:Label ID="lblApprovalURL" runat="server" Text="URL" CssClass="controllabel" meta:resourcekey="lblApprovalURLResource"></asp:Label>
    <asp:TextBox ID="txtApprovalURL" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="valApprovalURL" runat="server" ControlToValidate="txtApprovalURL" ErrorMessage="Please enter Valid Text" Text="*"></asp:RequiredFieldValidator>
    <actk:ValidatorCalloutExtender ID="extApprovalURL" TargetControlID="valApprovalURL" runat="server" Enabled="True"></actk:ValidatorCalloutExtender>
  </div>
</form>

  

1 个答案:

答案 0 :(得分:0)

通过执行以下操作,我能够让验证者做出反应。验证器非常简单,但我必须预测扩展器的ID以使其工作:

<script type="text/javascript">
        $(function () {
            $('#<%=chkEnableSilentPost.ClientID %>').click(function () {
                $("#<%=valApprovalURL.ClientID %>").toggle(this.checked);
                $("#extApprovalURL_popupTable").toggle(this.checked);
            });
        });

    </script>
    <form id="form1" runat="server">
        <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" />
        <div>
            <asp:CheckBox ID="chkEnableSilentPost" runat="server" Width="250px" Text="Enable" />
            <asp:Label ID="lblApprovalURL" runat="server" Text="URL" CssClass="controllabel" meta:resourcekey="lblApprovalURLResource"></asp:Label>
            <asp:TextBox ID="txtApprovalURL" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="valApprovalURL" runat="server" ControlToValidate="txtApprovalURL" ErrorMessage="Please enter Valid Text" Text="*"></asp:RequiredFieldValidator>
            <asp:ValidatorCalloutExtender ID="extApprovalURL" TargetControlID="valApprovalURL" runat="server" Enabled="True"></asp:ValidatorCalloutExtender>
        </div>
    </form>