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');
});
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);
}
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.
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 ?