Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate form before submit jquery

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?

like image 956
Maverick Avatar asked Jan 24 '15 07:01

Maverick


2 Answers

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.

like image 151
roland Avatar answered Oct 02 '22 20:10

roland


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>
like image 39
Farhat Aziz Avatar answered Oct 02 '22 19:10

Farhat Aziz