Eric Diviney
Eric Diviney

Reputation: 327

What is failing in my form validation function?

So I've tried making a function that loops through the elements of a form and checks the length of the elements, and if so, change the class so they can be styled differently. The code I have I assumed would work, and I'm not getting any errors in my console, so I can't pinpoint what is going wrong exactly. If someone could tell me why this won't work or how to fix it that would be awesome! Thankyou!

function validate_form(){
 var form = document.forms['form_name']; //store form into a variable
 var validated = true; // store return value for onsubmit attribute
     for(i=0; i<form.elements.length; i++){
      if(form.elements[i].value.length){  // check if form elements are empty
           form.elements[i].className = "validate_failed";  // if elements are empty, add a class that will style them
           validated = false;
           return validated;
    } else{
        validated = true;
        return validated;
    }
    return validated;
}
return validated;
}

Upvotes: 0

Views: 151

Answers (3)

ketan
ketan

Reputation: 390

Following code will work for empty element

if(!form.elements[i].value.length){ 

OR

if(form.elements[i].value.length === 0){ 

Upvotes: 0

mplungjan
mplungjan

Reputation: 177786

Try

function validate_form(){
  var form = document.forms['form_name']; //store form into a variable
  for(var i=0; i<form.elements.length; i++){
    if(form.elements[i].value.length===0){  // check if form elements are empty
      form.elements[i].className = "validate_failed";  // if elements are empty, add a class that will style them
      return false;
  }
  return true;
}

assuming

<form onsubmit="return validate_form()" ...

or make it all unobtrusive

window.onload=function() {
  document.forms['form_name'].onsubmit=function() {
    for(var i=0; i<this.elements.length; i++){
      this.elements[i].className = "";
      if(this.elements[i].value.length===0){  // check if form elements are empty
        this.elements[i].className = "validate_failed";  // if elements are empty, add a class that will style them
        return false;
      }
      return true;
    }
  }
}

Upvotes: 2

rosscj2533
rosscj2533

Reputation: 9323

Because your are returning validated during the first run through of the loop, you'll only ever check the first element of the form. You'll just want to set validated, and return it after the loop (or return when you first set it to false, depending on what you want to do).

Also, like Joe commented, you should have var i instead of just i so that i is not global.

Upvotes: 1

Related Questions