JulianJ JulianJ - 7 months ago 31
Javascript Question

Why does my form submit and ignore validation?

I am trying to figure out why jquery validation does not stop my form from being submitted? When the submit button is pressed the form posts correctly but seems to ignore the validation error (This field is required) even if the input field is left blank.

The form



$(document).ready(function() {
$("#message").hide();

//Define your validation rules.
$(function() {
$("#myform").validate({

});
$("#submitButtonId").on("click", function(e) {
var formdata = $("#myform").serialize();
//Post form data
$.post('php_includes/simple_insert.php', formdata, function(data) {
//Process post response
$("#message").html(data);
$("#message").fadeIn(500);
$("#message").fadeOut(500);
});

//Reset Form
$('#myform')[0].reset();
});
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>

<form class="form-inline" action="" id="myform" method="post">

<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="bill_cost"></label>
<div class="col-md-8">
<input id="bill_cost" name="bill_cost" type="text" placeholder="Bill Cost" class="form-control input-lg" required>

</div>
</div>

<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button type="submit" id="submitButtonId" name="submit1" class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>




Answer

Try this, use submitHandler to do other things for a valid form:

    $("#myform").validate({
        submitHandler : function() {
            var formdata = $("#myform").serialize();
           //Post form data
           $.post('php_includes/simple_insert.php', formdata, function(data){
             //Process post response
             $("#message").html(data);
             $("#message").fadeIn(500); 
             $("#message").fadeOut(500); 
           });

          //Reset Form
           $('#myform')[0].reset(); 

           }
        });