jQuery的验证:提交表单,只有当字段验证 [英] jQuery validate: submitting form only when fields are validated
问题描述
我用下面的code来验证我的形式。验证会很大,但我有一个问题提交表单的时候。而问题是:在表单提交到php文件每次被点击发送表格按钮,不管形式是未经验证。
我该如何解决呢?
我一直在研究submitHandler,但我不知道如何使用它与Ajax和序列化。
非常感谢!
<脚本>
$(文件)。就绪(函数(){
$(#表)。验证({
规则:{
名称: {
要求:真实的
},
LNAME:{
要求:真实的
}
},
消息:{
名称: {
要求:*为必填
},
LNAME:{
要求:*为必填
}
}
}); //端验证
$('#形式)。递交(函数(){
theUrl ='form.php的';
VAR PARAMS = $(本).serialize();
$阿贾克斯({
键入:POST,
网址:theUrl,
数据:参数,可以
过程数据:假的,
异步:假的,
成功:函数(结果){
//如果(数据=!)警报(数据);
}
});
//返回false;
}); //月底提交
}); //端文件准备就绪
< / SCRIPT>
您需要将您的AJAX请求code在验证插件的 submitHandler
参数。目前,AJAX请求正在运行的提交()
事件,具有平行于任何验证结果。试试这个:
$(文件)。就绪(函数(){
$(#表)。验证({
规则:{
名称:{要求:真实},
LNAME:{要求:真实}
},
消息:{
名称:{要求:*需要},
LNAME:{要求:*需要}
},
submitHandler:功能(形式){
theUrl ='form.php的';
VAR PARAMS = $(形式).serialize();
$阿贾克斯({
键入:POST,
网址:theUrl,
数据:参数,可以
过程数据:假的,
异步:假的,
成功:函数(结果){
//如果(数据=!)警报(数据);
}
});
}
}); //端验证
});
在
I'm using the code below to validate my form. The validation is going great but I have a problem when submitting the form. And the problem is: the form is submitted to the php file everytime the "Send form" button is clicked, no matter if the form is not validated.
How can I fix that?
I've been researching submitHandler but I don't know how to use it with ajax and serialize..
Thanks a lot!
<script>
$(document).ready(function(){
$("#form").validate({
rules: {
name: {
required: true
},
lname: {
required: true
}
},
messages: {
name: {
required: "* required"
},
lname: {
required: "* required"
}
}
}); //end validate
$('#form').submit(function() {
theUrl = 'form.php';
var params = $(this).serialize();
$.ajax ({
type: "POST",
url: theUrl,
data: params,
processData:false,
async:false,
success: function(result) {
//if (data != "") alert (data);
}
});
//return false;
}); //end submit
}); //end document ready
</script>
You need to place your AJAX request code in the submitHandler
parameter of the validate plugin. Currently the AJAX request is being run on the submit()
event, parrallel to any validation result. Try this:
$(document).ready(function(){
$("#form").validate({
rules: {
name: { required: true },
lname: { required: true }
},
messages: {
name: { required: "* required" },
lname: { required: "* required" }
},
submitHandler: function(form) {
theUrl = 'form.php';
var params = $(form).serialize();
$.ajax ({
type: "POST",
url: theUrl,
data: params,
processData: false,
async: false,
success: function(result) {
//if (data != "") alert (data);
}
});
}
}); //end validate
});
More information on the submitHandler
parameter.
这篇关于jQuery的验证:提交表单,只有当字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!