12

I have an HTML form. I am validating my form using jquery.validate.js and it works on submitting an event. I want to validate this form before submit get fired.

As per my research I have tried :

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

I want to validate the form Just before firing submit event. How to do this?

Amit Kumar
  • 3,384
  • 6
  • 25
  • 42
  • 1
    The plugin already does all this. Please explain better what is happening to make you think you need another event. Please show your validation code along with any other code needed to reproduce your issue. – Sparky Jan 24 '15 at 07:43
  • The OP states they want to validate the form _before_ submit, where the validation plugin only validates on submit. – ProfK Jan 07 '18 at 05:56

3 Answers3

29

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.

roland
  • 7,695
  • 6
  • 46
  • 61
  • 1
    The OP stated that he's using the jQuery Validation plugin. This plugin already takes care of that automatically by default. – Sparky Jan 24 '15 at 07:47
3
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>
Farhat Aziz
  • 131
  • 1
  • 10
0

This is how I deal with validation before jquery submit

<button onclick="$('#your_form').submit(
                     function(e){ e.target.reportValidity(); });
                ">

Credit goes to this post

Nam G VU
  • 33,193
  • 69
  • 233
  • 372