In your body tags add the following simple form:
Ok first thing to point out with our simple form is that the form tag its self. The form tag has a on submit event of “return validate();” that is awaiting the return of either true or false from the function validate().
Great, here we are forming our validate() function and in this function we are going to create a simple condition that checks each of our form fields to validate if their values are empty or not.
Lets point to our first form element like so:
We first point to our document, then to the name of our form “simpleForm”, and then to the name of our first form element “firstName”. Once we are pointing to the first form element, we check its value to see if indeed its value is empty or not (== “”).
Its that simple!
Now lets point to the other two form elements (lastName and message) to bring validation them as well. We can extend our conditional statement to the rest of our form elements by using whats called “Logical Operators” like so:
Notice how we are using the “||” between each form elements we point to? Basically we are saying “if firstName element value is equal to empty, OR (||) lastName element is equal to empty, OR (||) message element is equal to empty, then do the following”.
By using the “||” OR logical operators we can extend our condition to as many form elements as we like. There are more logical operators that you can read about here.
Great so now that we have extended out validation condition to check our three elements value’s, lets move on to the part of the function that cancels the form from being submitted if indeed one or more form element is empty like so:
if(document.simple_form.firstName.value == "" ||
document.simple_form.lastName.value == "" ||
document.simple_form.message.value == "")
alert("Please fill out all fields before clicking submit!");
And that’s it!
So with our simple condition we have pointed to each of our forms elements and peeked at its value. If the value of any of our form elements is equal to empty or rather nothing, we begin to alert a reminder to the user and halt the form from submitting to allow the user to correct the error. If all form fields pass our simple validation condition then our form continues to submit as normal.
Devin R. Olsen
THE BELOW FORM IS NOT A DEMO!!