Order Form Part 8: Form Validation, step 3
In the last step of our development project, we created code to validate the information being entered into fields on our for that had particular requirements of that data, specifically that only numeric data in entered into fields that we require to be numeric. This type of qualitative validation is not the only validation we need, however. If you look at our form, you will see that it says that "red denotes required information". If it's required, there should be something to make sure it's there!
This type of validation is subtly different from the last type we looked at.
In that validation, we checked the content of the field as soon as something was
put into the field by using the "onchange" event. When we're attempting to
ensure that required data has been entered, we have to allow the person typing
data into our form as much time as they might need to enter everything they
intend to. This means we can't check any fields as they are changed (or
not!) but instead, we have to wait until they are done entering data and click
our "submit" button. At that point we can see everything they have
entered, and can check whether or not something is missing. To get the
timing right for that, we'll need to change our
<form method="POST" action="submitted.html" name="ofrm">
statement. More on that in a minute!
if (theForm.Name.value == "")
alert("Please enter a value for the \"Name\" field.");
if (theForm.Email.value == "")
alert("Please enter a value for the \"Email\" field.");
Not too complicated! As you can see, each test is simply to determine whether or not the field has any content (ie, it's not equal to null.) This is a fairly simplistic test, but it's enough for our needs right now.
<form method="POST" action="submitted.html" onsubmit="return Validate(this) name="ofrm">
Using this format allows us to call the "Validate" function prior to taking the action specified. If all is good, the function will return with a "true" value and the action will be performed. If there's a problem, the alert in or function will have take place and the form submission will effectively be cancelled.
There are many enhancements that can be made to this type of validation. Your creativity will certainly allow you to come up with several. The important thing to remember here is the timing. If you think about the kinds of thing you might want to check, you will realize that this is a great opportunity to ensure that the data you receive is the kind of data that will serve your purpose.