Search code examples
javascriptvalidation

Form is still submitting despite returning false Vanilla Javascript


Here is my App.js

errorMessage=(validator, input, value)=> {
  const valid=validator(value)
  if (value==="") {
    input.nextElementSibling.style.display="inherit"
    return false 
  } else if (!valid && value!=="") {
    input.nextElementSibling.nextElementSibling.style.display="inherit"
    return false 
  }
  return true
}

const checkedCheckboxes=Array.from(checkboxes).filter(checkbox=> checkbox.checked);

validateCheckboxes=()=> {
  const checked=checkedCheckboxes.length;
  if (!checked) {
    fieldSetActivity.nextElementSibling.style.display="block"
    return false 
  }
  return true 
}



validateForm=()=> {
  if (!validateCheckboxes()) {
    return false 
  }
  return true
}

// validateForm=()=> {
//   Array.from(inputElements).forEach(element=> {
//     let value=element.value;
//     let input=element;
//     if (input===name) {
//       errorMessage(isValidName, input, value)
//     } else if (element===email) {
//       errorMessage(isValidEmail, input, value);
//     } else if (element===creditNumber) {
//       errorMessage(isValidCreditCard, input, value);
//     } else if (element===zip) {
//       errorMessage(isValidZipCode, input, value);
//     } else if (element===cvv) {
//       errorMessage(isValidCvv, input, value);
//     } else if (element==fieldSetActivity) {
//       validateCheckboxes()
//     }
//   });
// }


form.addEventListener('submit', validateForm);

I researched answers similar to this question, and the commented out code, I realized the booleans weren't reaching the parent validateForm function.

So I decided to test out one function, which was the validateCheckboxes function and implement a possible working solution in my form submit handler. But no, the form still submits despite the validate checkboxes function returning false.

Why is this happening?


Solution

  • EDIT:

    There are 2 things to be fixed in your code

    1. Returning true/false works if you have an onSubmit=return fun() in your <form> attribute. Since you are using a listener, you need to do event.preventDefault() from the validation function
    2. Your checkedCheckboxes is a const which means it will not be populated dynamically when the checkboxes are checked/unchecked. Move it into your checkbox validation method and make it a local variable using let

    With these changes, your validation bit would look as follows:

    validateCheckboxes=()=> {
    // 2. Local variable
    let checkedCheckboxes=Array.from(checkboxes).filter(checkbox=> checkbox.checked);
      const checked=checkedCheckboxes.length;
      if (!checked) {
        fieldSetActivity.nextElementSibling.style.display="block"
        return false;
      }
      return true;
    }
    
    validateForm=()=> {
      if (!validateCheckboxes()) {
      // 1. preventDefault instead of 'false'
         event.preventDefault();
      }
      return;
    }
    

    JSFiddle: https://jsfiddle.net/raghav_s/3e6s5tw8/

    OLD ANSWER:

    Offers a generic "How to validate your form"

    You need to call your JS validation before the form is submitted To do that, use the form's onSubmit attribute like this

    <form action="index.html" method="post" onSubmit="return validateForm()">
    

    JSFiddle: https://jsfiddle.net/raghav_s/3e6s5tw8/

    You can also do it using a form event listener and calling event.preventDefault() as specified in this MDN article

    Quoting the example from that page:

    JS:

    function logSubmit(event) {
      log.textContent = `Form Submitted! Time stamp: ${event.timeStamp}`;
      event.preventDefault();
    }
    
    const form = document.getElementById('form');
    const log = document.getElementById('log');
    form.addEventListener('submit', logSubmit);
    

    HTML:

    <form id="form">
      <label>Test field: <input type="text"></label>
      <br><br>
      <button type="submit">Submit form</button>
    </form>
    <p id="log"></p>