当远程调用返回 true 时,我需要阻止表单提交。我怎么能这样做?
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;
}
答案 0 :(得分:1)
引用OP :
“当远程调用返回 true 时,我需要阻止表单提交。”
那是倒退。您将返回false
来阻止提交并触发验证消息。
您不需要data
选项,因为默认情况下插件会发送字段值。您也不需要complete
选项,因为插件会自动捕获服务器响应。
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中设置自定义错误消息)
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;
}