• Hi there, I’m building a step form. I already managed to have multiple .tab’s in my <form> element. and it is possible to navigate to the next/prev tab. But validation is working well yet.

    I grab per tab all inputs like

    function validateForm(){
      var x, y, i;
      x = document.getElementsByClassName("tab");
      y = x[currentIndex].getElementsByTagName("input");
      
      for (i = 0; i < y.length; i++) {
    	validateField(y[i]);
      }
      
      if (valid) {
        document.getElementsByClassName("tab")[currentIndex].classList.add("finish");
      }
      return valid; // return the valid status
    }
    
    function validateField(input){
      if(isEmptyOrSpaces(input.value) && input.hasAttribute('required')){
          console.log(input.name + ' is required');
    	  input.classList.add('invalid');
          valid = false;
          return valid;
      }
      input.classList.remove('invalid');
      valid = true;
      return valid;
    }
    
    function isEmptyOrSpaces(str){
        return str === null || str.match(/^ *$/) !== null;
    }
    

    This mostly works for normal text inputs. But I’m getting into trouble when using radio’s/checkboxes. When you loop through all inputs per tab, it still sees any checkbox as a seperate input. and it will validate all of them, which always returns something good, because they already have an assigned value. I also tried using the FormData class in JS, but that apparently grabs all inputs from the entire <form> which isn’t good for validation per step.

    Does anyone have a solution?

    • This topic was modified 2 years, 3 months ago by janmoes.
Viewing 4 replies - 1 through 4 (of 4 total)
  • But I’m getting into trouble when using radio’s/checkboxes. When you loop through all inputs per tab, it still sees any checkbox as a seperate input.

    See this example:
    http://jsfiddle.net/matthewbj/hU4UY/

    If you have more than one checkbox to validate, use :checked with length to get number of check-boxes checked.

    Thread Starter janmoes

    (@janmoes)

    @a2hostingrj I’ve seen and tried that way yeah.

    In my example I just loop through all inputs. Which means it’s also going to loop through all name="gender" radio’s for example. The validation works, but it prints it for example two times, because of this, while I only need one validation message.

    Yeah, I did something like that few weeks ago. If I remember correctly, I think each radio button had an ID in order to avoid printing it two times.

    Thread Starter janmoes

    (@janmoes)

    So should I make like a switch, where I loop through all the inputs and check on the ID?
    Also how in that loop with my current code, could I change it so that atleast one radio button per radio button group needs to be required?

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Front end validation in step-form’ is closed to new replies.