我正在尝试使用jQuery validation remote method来检查值是否唯一 该规则在提交时添加,以防止在每次击键时触发该规则
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[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
,因为它没有等待远程规则完成它的调用。
This post建议在远程规则声明中使用async: false
,但这会冻结浏览器。
documentation中的示例没有使用它,因此它应该在没有它的情况下工作。
我的验证规则有问题吗?
答案 0 :(得分:0)
根据documentation,您应该将规则和验证方法直接附加到表单并使用submitHandler
回调,如下所示:
$('#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
}
}
我希望这有帮助!