使用jquery.validation.min.js进行远程验证



我正在尝试使用jquery.validate.min.js插件验证表单。

我使用了远程方法来验证手机是否已经存在。我使用了以下代码

$('#userprofileform').validate({
rules:
"UserForm[mobile]": {
remote: {
url: "<?php echo Yii::$app->request->BaseUrl.'/profile/check-mobile'; ?>",
type: "post",
data: {
mobile: function(){ return $("#userform-mobile").val(); }
}
}
},
},
messages: {
'UserForm[mobile]':{
remote:"Mobile already exists"
}
},
});

点击提交后,我写下了以下代码:

$('.userprofilesubmit').click(function(){
if (!$('#userprofileform').valid() === true){
return false;
}
});

验证工作正常。它正在显示信息。但表格被提交了两次。若我删除了远程验证,那个么表单只会提交一次。我观察到使用远程函数表单会被提交两次。如何避免这种情况?

Remote是一个ajax调用,它在响应中产生"true"或"false"。因此,如果您在ajax中提交表单,并且每当响应为true时,就会提交表单。如果您有4个字段的4个远程验证,那么表单将被提交4次。

因此,无论何时编写远程验证,都要使用async:false来避免表单提交,如下所示

$('#userprofileform').validate({
rules:
"UserForm[mobile]": {
remote: {
url: "<?php echo Yii::$app->request->BaseUrl.'/profile/check-mobile'; ?>",
type: "post",
data: {
mobile: function(){ return $("#userform-mobile").val(); }
},
async: false,
}
},
},
messages: {
'UserForm[mobile]':{
remote:"Mobile already exists"
}
},
});

最新更新