简体   繁体   中英

prevent jQuery form submit if validation fail

Hi I'm trying to prevent this AJAX submit form function when a validation fails on one of one of the various inputs.

Edit: What I want to know exactly is what I need to include in //Adult age validation and var handleFormSubmit to stop saveForm($('#quotecriteria_form')); and performAjaxSubmit(formData, url); from occurring.

Submit function:

  var handleFormSubmit = function( e ) {
e.preventDefault();

var $submit = $('button[type="submit"]');
$submit.addClass('loading');

// Save the contents of the form to session cookie
saveForm($('#quotecriteria_form'));

var formData = $('#quotecriteria_form').serialize();
var url = $('#quotecriteria_form').attr('action');
performAjaxSubmit(formData, url);
}

validation functions initialized:

IndexPageFunctions = {
init: function() {
//Validate date range
this.validateToDate();
this.validateFromDate();
//Validate adult age
this.validateAdultAge0();
this.validateAdultAge1();
this.validateAdultAge2();
this.validateAdultAge3();
//Validate child age
this.validateChildAge0();
this.validateChildAge1();
this.validateChildAge2();
this.validateChildAge3();
this.validateChildAge4();
this.validateChildAge5();
this.validateChildAge6();
this.validateChildAge7();
this.validateChildAge8();
},

One of the many validation functions:

//Adult age validation
validateAdultAge0: function() {
    $('button[type="submit"]').on('click', function() {
var inputVal = parseInt( $("input[name='adultAges[0]']").val());
if (inputVal < 18) {
    $("input[name='adultAges[0]']").css("border-color","red");
$("div#under18").addClass('show').removeClass('hidden');
}
        });
},

Define a boolean array outside the scope of all functions with an index for each input element:

var valid = [false,false,false...];

Set the original value to false if blank input should be considered invalid or true if the field is optional. In each of your validation handlers (like validateAdultAge0) change the corresponding flag accordingly. For example if you decide to map the validity of age0 to the 0th index then:

if (inputVal < 18) {
    $("input[name='adultAges[0]']").css("border-color","red");
    $("div#under18").addClass('show').removeClass('hidden');
    valid[0] = false;
}else{
    valid[0] = true;
}

Like someone in the comments pointed out, if the logic is the same for each of these functions you should be using an argument to specify the target input, not creating an entirely new function but I won't get into that here.

In handleFormSubmit you'll just need to check if all the flags in the valid array are set to true, if any one is false you can return:

for(var i=0;i<valid.length;i++){
    if(!valid[i]){
        return;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM