Onclick validate form, if valid only submit form

后端 未结 1 1132
独厮守ぢ
独厮守ぢ 2021-01-13 08:08

I have an html form that I first wish to validate with jQuery validation library jquery.validate.min.js and if form is valid, submit the form to a location.

相关标签:
1条回答
  • 2021-01-13 08:52

    Ideally I want to halt submission until form is validated.

    That's what the jQuery Validate plugin is already doing.

    Your code...

    $('#button1').on('click', function() {
        $("#issueform").valid();    //everything works upto here
        if($validator.noOfInvalids()===0){     //this code doesn't work
            $('#myModal').modal('toggle');
        }
    });
    

    As per docs, .valid() also returns a boolean, so the click handler part of your code above can be simplified greatly...

    $('#button1').on('click', function() {
        if ($("#issueform").valid()) {
            // do something here when the form is valid
            $('#myModal').modal('toggle');
        }
    });
    

    I know you already mentioned this, but the following is for the benefit of future readers:

    Please note that your click handler is required only because the input is a type="button".

    Alternatively, when using a type="submit", your click handler is not needed because the click is automatically captured by the plugin. Also, in that case, you would use the submitHandler option to contain any code to run when the form is valid.

    0 讨论(0)
提交回复
热议问题