【问题标题】:Limit RequiredFieldValidator to validate when a certain button is clicked限制 RequiredFieldValidator 以在单击某个按钮时进行验证
【发布时间】:2012-10-28 14:11:29
【问题描述】:

我正在开发一个 Web 应用程序,但我遇到了RequiredFieldValidator 的问题。

我有一个“插入电影”按钮和一个包含其他两个按钮(保存电影和取消)的 div,一个用于标题的文本框,一个用于描述的文本框和一个用于标题的 RequiredFieldValidator。 默认情况下不显示此 div。 这是我的问题: 当我单击插入时,在客户端我使用 javascript 隐藏插入按钮并显示我的 div。 单击按钮,我创建了一个 PostBack,我的 div 显示了RequiredFieldValidator 错误消息。 我不想要这种行为。我想在单击保存按钮后显示验证错误。 这是我的代码...

  <head runat="server">
    <title>Validation Test</title>
    <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            ValidatorEnable(document.getElementById('<%= TitleValidator.ClientID%>'), false);
        });
        function ShowInsertForm() {
            ValidatorEnable(document.getElementById('<%= TitleValidator.ClientID%>'), true);
            $('#InsertForm').show();
        }
        function HideInsertForm() {
            $('#InsertForm').hide();
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Insert" runat="server" Text="Insert Movie" OnClientClick="ShowInsertForm();"/>
    </div>
    <div id="InsertForm" style="display:none">
        <asp:Button ID="Save" runat="server" Text="Save Movie" onclick="Save_Click" OnClientClick="HideInsertForm();"/>
        <asp:Button ID="Cancel" runat="server" Text="Cancel Movie" CausesValidation="false" OnClientClick="HideInsertForm();"/>
        <br />
        Title<asp:TextBox ID="Title" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="TitleValidator" runat="server" 
            ErrorMessage="Please insert Title" ControlToValidate="Title"></asp:RequiredFieldValidator>
        <br />
        Description<asp:TextBox ID="Description" runat="server"></asp:TextBox>
    </div>
    </form>
</body>

【问题讨论】:

    标签: jquery asp.net validation


    【解决方案1】:

    1- 当您使用插入按钮仅用于客户端幻灯片功能时,我建议将 &lt;asp:button&gt; 控件替换为 html button tag 。这样就不再触发验证。

    2- 如果您必须使用 asp:button ,您可以将其 causeValidation 设置为 false 。更好的是,您可以通过编辑ShowInsertForm 函数来防止它导致post-back

        function ShowInsertForm() {
            ValidatorEnable(document.getElementById('<%= TitleValidator.ClientID%>'), true);
            $('#InsertForm').show();
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      相关资源
      最近更新 更多