jQuery验证不等待远程规则 [英] jQuery validation not waiting for remote rule
问题描述
我正在尝试使用 jQuery验证远程方法检查值是否唯一 在提交时添加了该规则,以防止在每次击键时触发该规则
I am trying to use jQuery validation remote method to check if a value is unique The rule is added on submit to prevent it from being fired on every keystroke
var Id = $("#id").val();
$('#form').on('submit', function (e) {
e.preventDefault();
var newValue = $('#input').val();
$('#input').rules('add', {
'remote': {
url: '/MyController/CheckValue',
type: 'POST',
data: {
id: Id,
value: newValue
}
},
messages: {
'remote': 'This value is not valid'
}
});
if ($('#form').valid()) {
window.console.log('valid')
// do something
}
$('#input').rules('remove', 'remote');
});
该操作在调用服务后返回true或false
The action returns true or false after a call to a service
[HttpPost]
public JsonResult CheckValue(int? id, string value)
{
bool available;
using (var myServiceClient = new MyServiceClient())
{
available = myServiceClient.IsValueAvailable(id, value);
}
return this.Json(available);
}
规则工作正常,但是$('#form').valid()
每次都会返回true
,因为它没有等待远程规则完成调用.
The rule works fine, but the $('#form').valid()
returns true
everytime because it is not waiting for the remote rule to finish it's call.
此帖子建议在远程规则声明中使用async: false
,但这会冻结浏览器.
文档中的示例未使用此文件,因此没有它应该可以工作.
This post suggests to use async: false
in the remote rule declaration but this freezes the browser.
The examples in the documentation are not using this, so it should be working without it.
我的验证规则有问题吗?
Is there something wrong with my validation rule ?
推荐答案
您应该附加的文档将规则和验证方法直接添加到表单,并使用submitHandler
回调,如下所示:
According to the documentation you should be attaching the rules and validation method directly to the form and using a submitHandler
callback like so:
$('#form').validate({
rules: {
inputName: {
remote: {
url: '/MyController/CheckValue',
type: 'POST',
data: {
id: Id,
value: newValue
}
}
},
messages: {
inputName: {
remote: 'This value is not valid'
}
},
submitHandler: function(form){
// Do Stuff with Form
}
}
我希望这会有所帮助!
这篇关于jQuery验证不等待远程规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!