[英]Form Validation with $.post()
I am using bassistance.de's Validation jQuery plugin to validate a form #signup-form
. 我正在使用bassistance.de的Validation jQuery插件来验证#signup-form
。 Instead of submitting the form data directly to the server the usual way, the form data should be submitted AJAX'ly via $.post()
. 与其按照通常的方式直接将表单数据提交给服务器,不如通过$.post()
AJAX'ly提交表单数据。
JS Code JS代码
// Validate form
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
}
});
// Submit to Serverside
$('#submit-btn').click(function() {
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
});
Problem: If a user entered data that does not pass the jquery validation, the click handler on #submit-btn
will still allow the form to be submitted! 问题:如果用户输入的数据未通过jquery验证,则#submit-btn
上的单击处理程序仍将允许提交表单! Is there a way to check that there are no validation errors? 有没有办法检查没有验证错误?
Try this: 尝试这个:
// Validate form
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
}
});
// Submit to Serverside
$('#submit-btn').click(function() {
if ($('.signup-form').valid()) {
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
}
});
The best way to do this is to use the submitHandler
option to validate: 最好的方法是使用submitHandler
选项进行验证:
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
},
submitHandler: function(form){
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
}
});
This will automatically be called once the form is valid. 表格有效后,系统会自动调用此功能。 No need to attach anything new to your submit button or the submit event. 无需在您的提交按钮或提交事件上添加任何新内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.