how to check if a form is valid programmatically using jQuery Validation Plugin

前端 未结 7 1855
余生分开走
余生分开走 2020-11-29 19:11

I have a form with a couple of buttons and I\'m using jQuery Validation Plugin from http://jquery.bassistance.de/validate/. I just want to know if there is any way I can che

7条回答
  •  半阙折子戏
    2020-11-29 19:58

    For a group of inputs you can use an improved version based in @mikemaccana's answer

    $.fn.isValid = function(){
        var validate = true;
        this.each(function(){
            if(this.checkValidity()==false){
                validate = false;
            }
        });
    };
    

    now you can use this to verify if the form is valid:

    if(!$(".form-control").isValid){
        return;
    }
    

    You could use the same technique to get all the error messages:

    $.fn.getVelidationMessage = function(){
        var message = "";
        var name = "";
        this.each(function(){
            if(this.checkValidity()==false){
                name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
                message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n
    "; } }) return message; }

提交回复
热议问题