Xoom3r Posted April 14, 2010 Share Posted April 14, 2010 I made a form validation function, it looks like this: function validate_form ( ) { valid = true; if ( document.contact.first.value == "" ) { valid = false; } else { valid = true; } if ( document.contact.last.value == "" ) { valid = false; } else { valid = true; } if ( document.contact.company.value == "" ) { valid = false; } else { valid = true; } if ( document.contact.phone.value == "" ) { valid = false; } else { valid = true; } if ( document.contact.cell.value == "" ) { valid = false; } else { valid = true; } if ( document.contact.email.value == "" ) { valid = false; } else { valid = true; } return valid; } I would like to do the following: if ( return valid == "false" ) { alert ("ONE OR MORE FIELDS ARE EMPTY"); } return valid; but it doesn't seem to stop the form from sending. Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted April 14, 2010 Share Posted April 14, 2010 How is the function being called? Is it via an onsubmit event or what? Quote Link to comment Share on other sites More sharing options...
Xoom3r Posted April 15, 2010 Author Share Posted April 15, 2010 yes, onsubmit. Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted April 15, 2010 Share Posted April 15, 2010 Can you show me? Quote Link to comment Share on other sites More sharing options...
seventheyejosh Posted April 15, 2010 Share Posted April 15, 2010 Firstly, comparing boolean false to the string false will not give you the results you're looking for. if(var==false) != if(var=="false") Secondly, if your first input is empty, and one after it isn't, you're resetting valid to true.. it isn't cascading properly. Thirdly, it is much easier to just declare a return var as true, then falsify it only if there is a need to. function validate(){ var retVal=true; if(document.getElementById('first').value==''){ retVal=false; }//end if if(document.getElementById('second').value==''){ retVal=false; }//end if // and so on. so if any are empty, it'll trigger the error. // then just return it: return retVal; }//end function Or if you wanna add some quick error messaging: function validate(){ var retVal=true; var alertVal=''; if(document.getElementById('first').value==''){ alertVal+="First Can't be blank!\n"; retVal=false; }//end if if(document.getElementById('second').value==''){ alertVal+="Second Can't be blank!\n"; retVal=false; }//end if // and so on. so if any are empty, it'll trigger the error. // then just return it: if(!retVal){ alert(alertVal); return false; }else{ return true; }//end if }//end function Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.