如何防止表单双重提交有Validator的形式?

时间:2013-09-11 15:55:48

标签: javascript jquery asp.net webforms validation

我的网页表单TextBoxValidator

<script src="../script/jquery-2.0.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("form").submit(function () {
            $('input[type=submit]', this).attr('disabled', 'disabled');
        });
    });
</script>
<form id="form1" runat="server">
    <asp:RequiredFieldValidator ID="v" runat="server" ControlToValidate="name" ErrorMessage="Required"></asp:RequiredFieldValidator>
    <asp:TextBox ID="name" runat="server"></asp:TextBox>
    <asp:Button ID="submit" runat="server" Text="Go" CausesValidation="true" />
</form>

我想在提交表单时停用提交button,但如果button TextBox无效,此代码也会停用提交Validator

我想要一种适用于所有ASP.NET验证器的方法,而不仅仅是RequiredFieldValidator

如何仅在真实提交中停用提交button

3 个答案:

答案 0 :(得分:1)

在禁用提交按钮之前,检查全局Page_IsValid变量是否设置为true

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title></title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("form").submit(function () {
                if (Page_IsValid)
                    $('input[type=submit]', this).prop('disabled', true);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:RequiredFieldValidator ID="v" runat="server" ControlToValidate="name" ErrorMessage="Required"></asp:RequiredFieldValidator>
        <asp:TextBox ID="name" runat="server"></asp:TextBox>
        <asp:Button ID="submit" runat="server" Text="Go" CausesValidation="true" />
    </form>
</body>
</html>

答案 1 :(得分:0)

$(document).ready(function () {
        $("form").submit(function (e) {
         if($.trim($('#<%=name.ClientID%>').val()) !='' ){ //if textbox not empty
            $('input[type=submit]', this).attr('disabled', 'disabled');
         }else{
            e.preventDefault();
         }
        });
    });

event.preventDefault

您可以使用.prop()

 $('input[type=submit]', this).prop('disabled', true);

答案 2 :(得分:0)

protected void submit_Click(object sender, EventArgs e) {
    if (name.Text != String.Empty) {
        submit.Enabled = false;
    } else {
        submit.Enabled = true;
    }
}

此代码没有javascript