sam sam - 2 months ago 12
jQuery Question

How to avoid or disable form submission when there are validation errors using Jquery Validator

I am actually facing an issue with my form validation using JQUERY Validator. The form is getting submitted even though it has validation errors on the fields. I am not sure how can we disable or not allow to submit form when there are validation errors on the fields? I believe bootstrap validator disables the button when there are validation errors. Though in my case I am using JQUERY VALIDATOR, so the form is being submitted and invoking an ajax call which i am invoking on submit. Please help!

form id="myform" class="form-horizontal" role="form" action="processAccount" method="post">
<h2><b style="color:#1E90FF;">Account</b></h2>
<div class="form-group">
<label for="Account Number" class="col-sm-3 control-label">Account Number</label>
<div class="col-sm-9">
<input type="text" id="accountNumber" name="accountNumber" placeholder="Account Number" class="form-control" autofocus required />
<!--<span class="help-block">Last Name, First Name, eg.: Smith, Harry</span>-->
</div>
</div>

<div class="form-group">
<label for="Company Number" class="col-sm-3 control-label">Company Number</label>
<div class="col-sm-9">
<input type="number" min="1" id="companyNumber" name="companyNumber" placeholder="Company Number" class="form-control" value=${companyNumber} required />
</div>
</div>

<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
<!-- <button type="submit" class="btn btn-info btn-block" onclick="doAjaxPost()">Search</button>
-->
<input type="button" style=" font-size: 18px;font-weight: bold; font-family: cursive;" id="processbutton" class="btn btn-info btn-block" value="Load" onclick="doAjaxPost()">

<div id="info" style="color: green; font-weight: bold;" font-size:380%;></div>

<%-- <p ><strong>${message}</strong></p>
--%>
</div>
</div>

</form> <!-- /form -->

<script>
$(document).ready(function () {

$('#myform').validate({ // initialize the plugin

rules: {
accountNumber: {
required: true,
minlength: 7,
maxlength: 7,
digits: true

},
companyNumber: {
required: true,
digits: true

},
submitHandler: function (form) {
console.log("Submitted!");
form.submit();
}
}
});

});

</script>



<script type="text/javascript">
function doAjaxPost() {
// get the form values
var accountNumber = $('#accountNumber').val();
var companyNumber = $('#companyNumber').val();
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var num = 1;
$.ajax({
type: "POST",
url: "./processAccount",
cache: false,
data: "accountNumber=" + accountNumber + "&companyNumber=" + companyNumber,
beforeSend: function(xhr) {
xhr.setRequestHeader(header, token);
},
success: function(response){
// we have the response
$('#info').html(response);
$('#accountNumber').val('');
if(companyNumber!=1)
{
$('#companyNumber').val(num);
}
},
error: function(e){
alert('Error While Request: ' + e);
}
});
}
</script>


Added SubmitHandler method under the JQUERY Validation block, However getting an error as Request method 'POST' not supported

submitHandler: function (form) {
console.log("Submitted!");
// get the form values
var accountNumber = $('#accountNumber').val();
var companyNumber = $('#companyNumber').val();
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var num = 1;
$.ajax({
type: "POST",
url: "./processAccount",
dataType: "json",
contentType: 'application/json',
cache: false,
data: "accountNumber=" + accountNumber + "&companyNumber=" + companyNumber,
beforeSend: function(xhr) {
xhr.setRequestHeader(header, token);
},
success: function(response){
// we have the response
$('#info').html(response);
$('#accountNumber').val('');
if(companyNumber!=1)
{
$('#companyNumber').val(num);
}
},
error: function(e){
alert('Error While Request: ' + e);
}
});
form.submit();
}
}
});
});

Answer

Change the submit button to type="submit" and remove the on click handler.

If you want to send it via AJAX you can still do that in the submitHandler callback.

Explanation: With setting your click handler to doAjaxPost() you're probably bypassing your validation and the submitHandler code gets never executed.

Additionally you have another error. submitHandler should be a sibbling of rules and not a child! It won't get called the way you use it. Use it like that instead:

$('#myform').validate({ // initialize the plugin
    submitHandler: function (form) {
         console.log("Submitted!");
         form.submit();
    },
    rules: {
        accountNumber: {
            required: true,
            minlength: 7,
            maxlength: 7,
            digits: true
        },
        companyNumber: {
            required: true,
            digits: true
        }
    }
});

See also at the API documentation https://jqueryvalidation.org/documentation/

For sending it via AJAX you should be able to call your doAjaxPost() instead of form.submit(); - at this place the validation already happened.

EDIT: As whished from the OP - here how to write it with his custom AJAX call:

submitHandler: function (form) {
      console.log("Submitted!");
      doAjaxPost();
}
Comments