Validate fields using JQuery validation without any submit?

前端 未结 5 2026
终归单人心
终归单人心 2020-11-29 02:39

I have a HTML5 web application with numerous user-entered fields, and I would like to do some client-side validation on those fields in javascript before sending them to the

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 03:10

    I've created a little helper. Just add this line of code and then you can use any button anywhere.

    $("body [data-submit-form]").on("click", function (event) {
        $("#" + $(event.target).data('submit-form')).valid();
    });
    
    

    Explanation: The jquery code listens for all clicks on an element with the attribute 'data-submit-form', in the listener the data-attribute gets extracted and then i trigger the valid method on the matching form.

    NOTE: if you want to submit the form if the form is valid use this code:

    $("body [data-submit-form]").on("click", function (event) {
        var form = $("#" + $(event.target).data('submit-form'));
        if (form.valid()) {
            form.submit();
        }
    });
    

提交回复
热议问题