I’ve been noticing lately how many student are creating multiple functions or if statements to do something that is possible in just a couple of lines, in this post I will try to explain how to use Arrays and Loops to validate a form, checking that it does not have any empty fields.
First you need to set up your form, here is the code for a simple log in form:
<form method="post" name="myform" action="login.php">
Username: <input type="text" id="username" name="username"/><br />
Password: <input type="password" id="pass" name="pass"/><br />
<input type="button" value="Log Me In" onClick="validate();"/></form>
You might have noticed that at the end of the form, instead of using ‘submit’ for the type I used ‘button’ instead. I do this to be 100% sure that the form will not be submitted unless it passes the JavaScript Validation. Please be aware that this method will bring a User Experience problem if he or she has JavaScript disabled, for this post please disregard the issue.
After you create your form, then we need to dive into the JavaScript code:
<script type="text/javascript" language="javascript">
function validate(){
//Create Fields Array
var fields = new Array;
var fields = [document.getElementById('username'),document.getElementById('pass')];
//Create Variable to Keep Track of Errors
var err = 0;
//Start Validation Loop
for (i=0;i<fields.length;i++){
//Check Fields in Array to Make Sure they are not Empty
if (fields[i].value == ""){
err++;
}
}//Close Loop
//Check That There are No Errors
if (err === 0){
//Submit Form
document.myform.submit();
}else {
//If there are errors, return false and alert the user
alert("Please Fill Out All Of The Fields");
return false;
}
}
</script>