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>
So there it is guys, all you have to do now is to add more fields to the fields array and it will loop around all of them to check them for empty spaces.
Here is a little more explanation on the script. The first thing that I did is to store my variables, I used an array for the fields being that they have a similar job in common and it will be easire to check them all like this. (An array is created when you have multiple objects with similar properties. For example you could make an array of Car Makes, Car Types, Regular Customers. This is more efficient than creating a different variable for each single item, now you just have to work with one.
After this we start the validation, this is done by looping trough that array to check that the fields are not empty. Let me explain how to create the loop, which is using the for statement. The first line will define where your loop starts, and how many time it will be runned.
Code: for (i=0;i<fields.length;i++) Explanation: for(variable that will be keeping track of how many loops have passed ; how many times will the loop run (the .length property only gives out the array size, so that we can run it that many times ; and finally this step will add one to the loop variable for the next run)
Every time the loop runs, the code between the brackets it???s what is run multiple time. In this case we did an if statement to check the field value. if it finds an empty field it will add one to theξerr variable. After the loop is completed,ξ then we do anotherξif statement to check that there are no errors, if they are none then the form is submitted, is there is an error then it will alert the user and return false.
Hope this helped you out, please leave any comments or suggestions below.
www.GilbertoCortez.com // Interactive Solutions and Web Development