Validate form before submit jquery

前端 未结 2 1154
别跟我提以往
别跟我提以往 2021-01-11 21:17

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.

As per my R&

相关标签:
2条回答
  • 2021-01-11 21:41

    You can mimic the default jQuery plugin behaviour as follows:

    Test if the form is valid; if not prevent the default action from occurring using 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.

    0 讨论(0)
  • 2021-01-11 21:43
    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>
    
    0 讨论(0)
提交回复
热议问题