在提交之前检查jQuery验证的表单提交
我使用Ajax和jQuery来验证并提交表单中的信息。我遇到的问题是,当我单击提交按钮时,表单会在执行验证检查并显示错误之前立即向服务器提交信息?在提交之前检查jQuery验证的表单提交
我不确定这里的问题是什么,所以任何输入都会很棒!
干杯
$('#submit_second').click(function() {
//remove classes
$('#second_step input').removeClass('error').removeClass('valid');
var emailPattern = /^[a-zA-Z0-9._-][email protected][a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var phonePattern = /^\+?[0-9]{0,15}$/ ;
var fields = $('#second_step input[type=text]');
var error = 0;
fields.each(function() {
var value = $(this).val();
if(value.length<1 || value==field_values[$(this).attr('id')] || ($(this).attr('id')=='email' && !emailPattern.test(value))) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
if(value.length<1 || value==field_values[$(this).attr('id')] || ($(this).attr('id')=='phone' && !phonePattern.test(value)) ) {
$(this).addClass('error');
$(this).effect("shake", { times:3 }, 50);
error++;
} else {
$(this).addClass('valid');
}
});
if(!error) {
//update progress bar
$('#progress_text').html('66% Complete');
$('#progress').css('width','226px');
//slide steps
$('#second_step').slideUp();
$('#fourth_step').slideDown();
} else return false;
});
$('#submit_second').click(function(){
url =$("input#url").val();
yourname =$("input#yourname").val();
email =$("input#email").val();
phone =$("input#phone").val();
//send information to server
var dataString = 'url='+ url + '&yourname=' + yourname + '&email=' + email + '&phone=' + phone;
alert (dataString);
$.ajax({
type: "POST",
url: "#",
data: "url="+url+"&yourname="+yourname+"&email="+email+'&phone=' + phone,
cache: false,
success: function(data) {
console.log("form submitted");
alert("success");
}
});
return false;
});
$('form_to_validate').submit(function() {
// .. stuff
});
我猜你要寻找的是这样的:
$('#submit_second').submit(function(evt){
evt.preventDefault();
...
});
退房jQuery的文档:http://api.jquery.com/event.preventDefault/
不认为这会工作?我不想阻止表单提交,只是在首次检查验证后才发生! 如果我将所有的代码移到一个函数中,你认为这有助于解决问题吗? – DannyW86 2012-07-09 14:45:14
是的。如果验证失败,您可以调用preventDefault,否则表单将正确提交。 – admenva 2012-07-09 18:42:11
我在最后的欢呼声中解决了问题! http://stackoverflow.com/questions/11413111/problems-with-jquery-form-validation-and-ajax-submit/11413385#11413385 – DannyW86 2012-07-10 13:48:49
我想这一点,但表单有多个部分在每个部分提交后使用jquery加载dynamicaly,因此它在那里正常工作是2个部分,每个都有一个提交按钮,第一部分工作正常,但作为即时通讯尝试验证并提交数据到服务器在同一时间在第二阶段似乎提交数据之前,它执行验证检查的方式我有我的代码结构? – DannyW86 2012-07-09 14:34:41
向我们显示您的问题中的HTML。 – 2012-07-10 07:34:06