开发者

jquery - validation plugin

I make a simple validation plugin, that return false if input fail validation, the problem开发者_开发技巧 is this plugin only works with one input at a time. I want it to work with all input at the same time.

the code

$.fn.validate = function(options){
    var defaults = {
        required:true,
        minChar:0,
        maxChar:0
    },
    o = $.extend({},defaults, options);
    this.each(function(){
        var $this=$(this);
        var val = $this.val();
        if(o.required==true && val==''){
            return false;
        }else if(o.minChar>0 && val.length < o.minChar ){
            return false;
        }else if(o.maxChar>0 && val.length >o.maxChar ){
            return false;   
        }
        else{return true;}
    });
}

call

if(!$('#name').validate()){
    $('.name_inline_error').text('require name');
    return false;// return false to stop ajax form submiting
}

if(!$('#email').validate()){
    $('.email_inline_error').text('require email');
    return false;// return false to stop ajax form submiting
}

What the code will do is, if two inputs are empty, the plugin will only tell the name input error, only when the name input was validated, the form will tell the email input error. While, I want to see two errors at the same time.


When you return, you are skipping the rest of your function. Try something like this:

valid = true;

if(!$('#name').validate()){
  $('.name_inline_error').text('require name');
  valid = false;  
}

if(!$('#email').validate()){
  $('.email_inline_error').text('require email');
  valid = false;
}

return valid;

(+1 to Matt Ball's comment, however -- rolling your own on this one is going to take a long time.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜