So I just found that you can add any custom validation logic. If it's simple enough it's not a problem, right?
$.validator.addMethod('customRule',function(val, el){
return val > 2;
},'value cannot be smaller than 2');
$('#myInput').rules('add', { customRule : true });
now, even if you have something a little bit more difficult (a REST call for example) it still can be done:
$.validator.addMethod('customRule',function(val, el){
var validator = this;
$.get('checkValueOnServer',val).done(function(isValid){
if(!isValid){
var errors = {};
errors[el.name] = 'server says: value does not look right!';
validator.showErrors(errors);
}
validator.stopRequest(el, isValid);
})
return 'pending';
},'');
now, in my case I need to call a function with a callback, something like that
$.validator.addMethod('customRule',function(val, el){
var validator = this;
checkValueOnServer(el, function(isValid){ // so function runs for a few secs and returns a callback with a result
if(!isValid){
var errors = {};
errors[el.name] = 'called function says: value does not look right!';
validator.showErrors(errors);
}
validator.stopRequest(el, isValid);
});
return 'pending';
},'');
You see just a good old callback, not deferred
object. So in the later case if I call
$('form').valid()
it reports it's true, although custom called function reports that the validation rule didn't pass and the element is highlighted and error message is shown. So what's wrong? What's the right way to tell that thing: the form is invalid?