简体   繁体   中英

Google HTML Form submits despite validation

I have a form working in as much as it writes to the spreadsheet. The input fields have the status of required and the form calls the script on submit.

After searching I have discovered that the validation needs to happen before the submit but I am struggling to make it work. Any advice? The form code is here:

Form Code

and I have tried a solution suggested here: Check required fields on Form

by adding the <div class="ss-item-required"> tags and including the code

    function formcheck() {
  var fields = $(".ss-item-required")
        .find("select, textarea, input").serializeArray();

  $.each(fields, function(i, field) {
    if (!field.value)
      alert(field.name + ' is required');
   }); 
  console.log(fields);
}

but all I got on the console was class undefined errors.

So your code as it is has two main issues causing your problem. Firstly, the validation function for checking the form, formCheck() , isn't actually within any containing <script> tags - so this needs to be changed for the code to be executed as a script.

Secondly, to prevent the form from submitting when the validation fails, you need to actually execute the check for the outcome of the validation before allowing the execution of the runGoogleScript() :

<button type="submit" id="submitButton" class="blue" onclick="return formCheck();">SUBMIT ENTRY</button>

If the form validates within formCheck() then you can execute the runGoogleScript() with something like:

function formCheck() {

    var flag = false;

    var fields = $(".ss-item-required").find("select, textarea, input").serializeArray();

    $.each(fields, function(i,field) {
        if(!field.value) {
            alert(field.name +' is required');
            flag = true; //Flag that the form is invalid
        }
    });

    //If form is valid, 'flag' will be false
    if (!flag) {
        runGoogleScript(); //Execute script
    }

    return false; //If the validation fails

    console.log(fields);

}

Hope this helps.

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