Basics of Form Validation
When the user clicks on a submit button or presses the return/enter key while in a form field, an event occurs that can be caught with the
return false; statement explicitly cancels the submit event. For example, the following form will never be submitted:
<form action="Process.html" onsubmit="return false;">
<!--Code for form fields would go here-->
<input type="submit" value="Submit Form">
Note that, for brevity, we here use the
onsubmit attribute to listen for the submit event; we'll generally listen for the submit event (and other events) with
Of course, when validating a form, we only want the form not to submit if something is wrong. We can use the preventDefault() method to stop the form from submitting if the data entered by the user doesn't match what we expect. Let's look at an example
There are a few improvements we can make on the last example.
One problem is that the
validate() function only checks for one problem at a time. That is, if it finds and error, it reports it immediately and does not check for additional errors. Why not just tell the user all the mistakes that need to be corrected, so (s)he doesn't have to keep submitting the form to find each subsequent error?
Another problem is that the code is not written in a way that makes it easily reusable. For example, checking for the length of user-entered values is a common thing to do, so it would be nice to have a ready-made function to handle this.
These improvements are made in the example below.