jQuery验证-防止在远程提交 [英] jQuery Validation - prevent submit on remote
问题描述
当远程调用结果返回 true 时,我需要阻止提交表单.我该怎么办?
I need to prevent form from submitting when remote call returns true as result. How can I do this?
JS代码:
var userForm = $('#user-form');
userForm.validate({
rules : {
email : {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST',
data: function(){
return $('#email').val()
},
complete: function(data){
if(data.responseText.trim() == 'true'){
return false;
}
}
}
}
}
});
服务器端:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
echo false;
else:
echo true;
endif;
}
推荐答案
引用OP :
当远程调用返回结果为 true 时,我需要阻止提交表单."
"I need to prevent form from submitting when remote call returns true as result."
那是倒退.您将返回false
阻止提交并触发验证消息.
That's backwards. You would return false
to block the submit and trigger the validation message.
您不需要data
选项,因为插件默认发送字段值.您也不需要complete
选项,因为该插件会自动捕获服务器响应.
You don't need the data
option since the plugin sends the field value by default. You also don't need the complete
option as the plugin captures the server response automatically.
JavaScript:
JavaScript:
var userForm = $('#user-form');
userForm.validate({
rules: {
email: {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST' // default is GET
}
}
}
});
服务器端:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
// setting message in PHP allows you to dynamically have any message
echo json_encode('name is already taken');
else:
echo true;
endif;
}
替代
(在JavaScript中设置的自定义错误消息)
(Custom error message set in JavaScript)
JavaScript:
JavaScript:
var userForm = $('#user-form');
userForm.validate({
rules: {
email: {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST' // default is GET
}
}
},
messages: {
email: {
remote: "name is already taken"
}
}
});
服务器端:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
echo false;
else:
echo true;
endif;
}
文档: http://jqueryvalidation.org/remote-method/
这篇关于jQuery验证-防止在远程提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!