jquery custom validation method with a callback -
so found can add custom validation logic. if it's simple enough it's not problem, right?
$.validator.addmethod('customrule',function(val, el){ return val > 2; },'value cannot smaller 2'); $('#myinput').rules('add', { customrule : true }); now, if have little bit more difficult (a rest call example) still can 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 not right!'; validator.showerrors(errors); } validator.stoprequest(el, isvalid); }) return 'pending'; },''); now, in case need call function callback, that
$.validator.addmethod('customrule',function(val, el){ var validator = this; checkvalueonserver(el, function(isvalid){ // function runs few secs , returns callback result if(!isvalid){ var errors = {}; errors[el.name] = 'called function says: value not right!'; validator.showerrors(errors); } validator.stoprequest(el, isvalid); }); return 'pending'; },''); you see old callback, not deferred object. in later case if call
$('form').valid() reports it's true, although custom called function reports validation rule didn't pass , element highlighted , error message shown. what's wrong? what's right way tell thing: form invalid?
when using custom validation method, function typically returns true or false.
if custom validation function returns
true, element passed validation , there no error message triggered. http://jsfiddle.net/kcqy5/1/if custom validation function returns
false, element failed validation , error message displayed. http://jsfiddle.net/kcqy5/2/if custom validation function not return
trueorfalse, results not seem predictable. http://jsfiddle.net/kcqy5/
yours returning string contains text 'pending', required error message displayed though form passes validation. usage outside scope of documentation...
method callback
actual method implementation, returning true if element valid. first argument: current value. second argument: validated element. third argument: parameters.
Comments
Post a Comment