0

I'm trying to create a multi step form with validation based on required fields. The current Javascript I'm using is just looking for fields that are filled in to validate the form. But how do I make it ignore fields that are not marked as "required" in the html?

Thank you!

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
JeepGirl
  • 21
  • 4

1 Answers1

0

But how do I make it ignore fields that are not marked as "required" in the html?

The following solution checks for the required property in the input elements. So in the for loop, the first thing you would do is if(!y[i].required){ continue; }, in other words if y[i].required is undefined, then continue (or skip this iteration).

function validateForm() {
  // This function deals with validation of the form fields
  var x, y, i, valid = true;
  x = document.getElementsByClassName("tab");
  y = x[currentTab].getElementsByTagName("input");
  // A loop that checks every input field in the current tab:
  for (i = 0; i < y.length; i++) {
    // --> if y[i].required is undefined... skip to the next <--
    if(!y[i].required){ continue; }
    // If a field is empty...
    if (y[i].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // If the valid status is true, mark the step as finished and valid:
  if (valid) {
    document.getElementsByClassName("step")[currentTab].className += " finish";
  }
  return valid; // return the valid status
}