jQuery 在提交jquery之前验证表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28123236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:31:20  来源:igfitidea点击:

Validate form before submit jquery

jqueryformsjquery-validateform-submit

提问by Maverick

I have a html form. i am validating my form using jquery.validate.js and it works on submit event. I want to validate this form before submit get fired.

我有一个 html 表单。我正在使用 jquery.validate.js 验证我的表单,它适用于提交事件。我想在提交被解雇之前验证此表单。

As per my R&D i have tried :

根据我的研发,我尝试过:

$('#my-form').on('before-submit',function(){
   alert('Before submit performed');
});

I want to validate form Just before firing submit event. Can any one tell me how to do this?

我想在触发提交事件之前验证表单。谁能告诉我如何做到这一点?

Many Thanks,

非常感谢,

M

回答by roland

You can mimic the default jQuery plugin behaviour as follows:

您可以模仿默认的 jQuery 插件行为,如下所示:

Test if the formis valid; if not prevent the default action from occurring using preventDefault():

测试是否form有效;如果不使用以下方法阻止默认操作发生preventDefault()

$(document)
.on('click', 'form button[type=submit]', function(e) {
    var isValid = $(e.target).parents('form').isValid();
    if(!isValid) {
      e.preventDefault(); //prevent the default action
    }
});

EDIT: this comes in handy if you want to fine-tune your validation test i.e. validating some controls conditionally.

编辑:如果你想微调你的验证测试,即有条件地验证一些控件,这会派上用场。

回答by Farhat Aziz

First validate and then use submit handler


 <script>
    $().ready(function() {
        $('#addNew').validate({
            rules: {
                patient_first_name: "required",
                patient_last_name: "required"
            },
            messages: {
                patient_first_name: "Please enter first name",
                patient_last_name: "Please enter last name"

            },
            submitHandler: function(form) {
                form.submit();
            }

            // any other options and/or rules
        });
    });
    </script>