Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not submit a form if validation is false

How can I make sure the form won't submit if one of the validations is false?

$('#form').submit(function(){
    validateForm1();
    validateForm(document.forms['dpart2']);
    validateForm(document.forms['dpart3']);                     
}); 
like image 625
sanders Avatar asked Mar 20 '09 09:03

sanders


4 Answers

$('#form').submit(function(){
    return (validateForm1() &&
            validateForm(document.forms['dpart2']) &&
            validateForm(document.forms['dpart3']))
});

Basically, you return false in the event handler function.

like image 93
Tamas Czinege Avatar answered Oct 15 '22 01:10

Tamas Czinege


If the function returns false, form won't be submitted.

$('#form').submit(function(){
    return  validateForm1() 
            && validateForm(document.forms['dpart2']) 
            && validateForm(document.forms['dpart3']);                                         
              }
});
like image 32
vartec Avatar answered Oct 15 '22 00:10

vartec


Okay, some of the other solutions will have a lazy fail... you probably want all your validation to run, so that all errors are displayed. The presumption is that your validation methods will return false if they fail.

$("#myform").submit(function() {

    var ret = true;
    ret = validateForm1() && ret;
    ret = validateForm(document.forms['dpart2']) && ret
    ret = validateForm(document.forms['dpart3'])) && ret
    return ret;

});

This way all your validators will be called, but the Boolean value for any failure, will result in a fail.

like image 4
Tracker1 Avatar answered Oct 14 '22 23:10

Tracker1


If validateForm(...) and validateForm1() return a boolean (true means that no validation error occurred), then you try to do that :

$('#form').submit(function(){
    if (!validateForm1() || !validateForm(document.forms['dpart2']) || !validateForm(document.forms['dpart3'])) {
        return false;
    }
});
like image 3
Romain Linsolas Avatar answered Oct 15 '22 00:10

Romain Linsolas