2

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?

4

1 回答 1

3

使用自定义验证方法时,该函数通常只返回 atrue或 a false

您的仅返回一个包含 text 的字符串,'pending'即使required表单通过验证也会显示错误消息。您的使用超出了文档的范围...


根据文档

method Callback
实际的方法实现,如果元素有效则返回 true。第一个参数:当前值。第二个参数:经过验证的元素。第三个参数:参数。

于 2013-04-18T21:14:35.150 回答