带有提交处理程序的 jQuery 验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1218409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:56:29  来源:igfitidea点击:

jQuery validation with submit handler

jqueryjquery-validate

提问by

I setup the form validation using jQuery validation plug-in's validate method and I have a submit handler that modifies the input element's value (I use YUI editor and it needs saveHTML() call to copy the iframe's content to the textarea element.). When submitting the form, I want the validator to validate the form after executing my submit handler. But it doesn't execute my submit handler if it is registered after the validate call.

我使用 jQuery 验证插件的 validate 方法设置表单验证,并且我有一个修改输入元素值的提交处理程序(我使用 YUI 编辑器,它需要 saveHTML() 调用将 iframe 的内容复制到 textarea 元素。)。提交表单时,我希望验证器在执行我的提交处理程序后验证表单。但是,如果它在验证调用之后注册,则它不会执行我的提交处理程序。

For example,

例如,

<form id="form1" action="/test">
    <input type="text" name="txt1" id="txt1" />
    <input type="submit" value="submit" />

$(document).ready(function() {
    $("#form1").submit(function() {
        $("#txt1").val("123456");
    });

    $("#form1").validate({
        rules: {
            txt1: {
                maxlength: 5
            }
        }
    });
});

The form is validated after my submit handler so submit is canceled.

在我的提交处理程序之后验证表单,因此提交被取消。

$(document).ready(function() {
    $("#form1").validate({
        rules: {
            txt1: {
                maxlength: 5
            }
        }
    });

    $("#form1").submit(function() {
        $("#txt1").val("123456");
    });
});

However if I change the order the form is validated before my submit handler.

但是,如果我更改订单,则在提交处理程序之前验证表单。

回答by Darin Dimitrov

You could use the beforeSubmitcallback to set values:

您可以使用beforeSubmit回调来设置值:

$(function() {
    $('#form1').validate({
        rules: {
            txt1: { maxlength: 5 }
        },
        beforeSubmit: function(arr, $form, options) {
            $('#txt1').val('123456');
            return true;
        }
    });
});

回答by RaYell

Try

尝试

$(document).ready(function() {
    $("#form1").submit(function() {
        $("#txt1").val("123456");

        $("#form1").validate({
            rules: {
                    txt1: {
                            maxlength: 5
                    }
            }
        });
    });
});

This way validation will be triggered by your submit event handler.

这种方式验证将由您的提交事件处理程序触发。

回答by Jesús Ascama

You must use $("form").validate().resetForm();

你必须使用 $("form").validate().resetForm();

回答by Xaimaran

You can simply use this:

你可以简单地使用这个:

var validForm = false;

SubmittingForm = function () 
{    
     //Validate Statements...
     validForm = true;
     $("#form1").submit();
}

$(document).ready(function () {
$("#form1").validate({
            submitHandler: function (form) {
                if (validForm)
                    $("#form1").submit();
                else
                    SubmittingForm();
            },
            rules: ...
}

回答by vijay pancholi

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script src="jquery-3.1.1.min.js"></script>
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
  
<style type="text/css">
p1{
    color:orange;
}
p2{
    color:green;
}

 

body{
                
                }
        
            #form label{
                font:bold 11px arial;
                color: #565656;
                padding-left: 1px;
            }
            #form label.mandat{color:red;}
            #form input[type="text"]{
                height: 30px;
                margin-bottom: 8px;
                padding: 5px;
                font: 12px arial;
                color: olive;
            }
            #form textarea{
                width: 340px;
                height: 80px;
                resize: none;
                margin: 0 0 8px 1px;
                padding: 5px;
                font: 12px arial;
                color: yellow;
            }
            #form img{
                margin-bottom: 8px;
            }
            #form input[type="submit"]{
                background-color: #0064aa;
                border: none;
                color: #fff;
                padding: 5px 8px;
                cursor: pointer;
                font:bold 12px arial;
            }
            .error{
                border: 1px solid olive;
            }
            .cap_status{
                width: 350px;
                padding: 10px;
                font: 14px arial;
                color: #fff;
                background-color: #10853f;
                display: none;
            }
            .cap_status_error{
                background-color: #bd0808;                
            }


</style>
  
  <script>
  
   $.validator.addMethod("error1", function(value, element, error) {          
    return error.test(value);
});

   $.validator.addMethod("error2", function(value, element, error) {          
    return error.test(value);
});

 $.validator.addMethod("error3", function(value, element, error) {          
    return error.test(value);
}); 
$.validator.addMethod("error4", function(value, element, error) {
   return error.test(value);
});

    $.validator.addMethod("error5", function(value, element, error) {          
    return error.test(value);
}); 
  
$.validator.addMethod("error6", function(value, element, error) {          
    return error.test(value);
});

$.validator.addMethod("error7", function(value, element, error) {          
    return error.test(value);
});
$.validator.addMethod("error8", function(value, element, error) {          
    return error.test(value);
} );






  $(function() {
  
  
    $("#register-form").validate({
    
       
        rules: {
           
               firstname: {
                required: true,
                error1: /^[A-Za-z']+( [A-Za-z']+)*$/
                
            },
            lastname: {
                required: true,
                error2: /^[A-Za-z']+( [A-Za-z']+)*$/
              
            },
                address: {
                required: true,
                error3: /^[0-9,./\-_ a-zA-Z''\s a-zA-Z0-9]+$/
                
            },
            pincode: {
                required: true,
                error4: /^[1-9][0-9]{5}$/
                
            },


             city:  {
                required: true
            },


            dob:  {
                required: true
            },
            
           

            
              mobileno: {
                required: true,
                error5: /[7|8|9][0-9]{9}/,
                maxlength: 10
            },
            emailid: {
                required: true,
                error6: /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)+$/
                
            },

            
            
            password: {
                required: true,
                error7: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{6,16}$/
              
            },
            cpassword: {
                required: true,
                error8: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{6,16}$/,
               equalTo: "#password"
               
            },
           
       
        
        


        },

        messages: {


          firstname: {
                required: "<p1>Please enter your first name</p1>",
               
                error1: "<p2>name must be content alphabet</p2>"
            }, 
            lastname: {
                required: "<p1>Please enter your last name</p1>",
                
                error2: "<p2>name must be content only alphabet</p2>"
            }, 




            address: {
                required: "<p1>Please enter address</p1>",
                
                error3: "<p2>name must be content alphabet with no</p2>"
            },   


            pincode: {
                required: "<p1>Please enter pincode</p1>",
                
                error4: "<p2>6 digit number only require</p2>"
            },

             city: {
            required: "<p1>Please choose city</p1>"
        },


          dob: {
            required: "<p1>Please enter date of birth</p1>"
        },


            mobileno: {
                required: "<p1>require contact no</p1>",
                
                error5: "<p2>no start with 7,8,9 with 10 digit</p2> "
            },



            emailid: {
                required: "<p1>require email </p1>",
                
                error6: "<p2>please enter email with @ and . </p2> "
            },




            password: {
                required: "<p1>Please provide a password",
                error7: "<p2> password require at least lower,upper,numeric,alphabet,special character</p2>"
            },
             cpassword: {
                required: "<p1>Please provide a password</p1>",
               error8: "<p2>password require at least lower,upper,numeric,alphabet,special character</p2>",
               equalTo: "<p1>Password not match</p1>"
            }, 

            
            
           
            

        },
        
        submitHandler: function(form) {
            form.submit();
        }
    });

  });
  
  </script>
  

</head>
<body>

 <div style='margin:0 auto'>

<form name= "" id="register-form" action="loginformjq.php"  method="post">
<div id="form">
<table  border="1" padding="2" cellpadding="2" width="20%" bgcolor="lightblue" align="center" cellspacing="2">

<tr>
<td colspan=2>
<center><font size=4><p style="color: purple"><marquee direction="left" behavior="alternate" style="border:solid olive">Student Registration Form</marquee></p></font></center>
</td>
</tr>

<tr>
<td><p style="color: yellow">Firstname</p></td>
<td><p class="error"><input type="text" name="firstname" id="firstname" size="20" value=""></p>
</td>
</tr>

<tr>
<td><p style="color: yellow">Lastname</p></td>
<td><p class="error"><input type="text" name="lastname" id="lastname" size="20" value=""></p>
</td>
</tr>



<tr>
<td><p style="color: yellow">Address</p></td>
<td><p class="error"><input type="text" name="address" id="address" size="20"></p>
</td>
</tr>

<tr>
<td><p style="color: yellow">Pincode</p></td>
<td><p class="error"><input type="text" name="pincode" id="pincode" size="20"></p>
</td>
</tr>



<tr>
<td><p style="color: yellow">City</td>
<td><select name="city">
<p1><option value="" selected>select city</option>
<option value="New Delhi">NEW DELHI</option>
<option value="Mumbai">MUMBAI</option>
<option value="Goa">GOA</option>
<option value="Patna">PATNA</option>
</select></p1>
</td>
</tr>





<tr>
<td><p style="color: yellow">DOB</p></td>
<td><p class="error"><input type="date" name="dob" id="dob" size="20"></p>
</td>
</tr>

<tr>
<td><p style="color: yellow">MobileNo</p></td>
<td><p class="error"><input type="text" name="mobileno" id="mobileno" size="20"></p>
</td>
</tr>



<tr>
<td><p style="color: yellow">EmailId</p></td>
<td><p class="error"><input type="text" name="emailid" id="emailid" size="20"></p>
</td>
</tr>



<tr>
<td><p style="color: yellow">password</p></td>
<td><p class="error"><input type="password" id="password" name="password" size="20"></p>
</td>
</tr>

<tr>
<td><p style="color: yellow">cpassword</p></td>
<td><p class="error"><input type="password" id="cpassword" name="cpassword" size="20"></p>
</td>
</tr>
                  

<tr>
<p style="color: yellow"></p>
<td colspan="1"><input type="submit" value="submit"></td>

</tr>
</table>
</div>
</form>
  

        </div>
</body>
</html>