Web Development - Use "Return" To Make JavaScript Form Validation Work

Perhaps the first thing people talk about when discussing the role of client-side JavaScript is form validation. You've probably heard something like this: "Use JavaScript to validate form entries so you don't waste the user's time with unnecessary trips to the server."

But as simple and obvious as that advice is, there's a little piece that's easy to forget: namely, how to properly hook your validation code into the submission process. For instance, let's say you have a nice little form. When the user presses the Submit button, it posts to another page--say, EmailFormPost.asp. Then, you write a nice little validation script to check that the form is entered correctly (e.g., all required fields are filled, no obvious syntax errors). If everything's correct, you make your function return true, otherwise false.

But one little tiny thing's lacking: How do you make sure the submit takes place only if the function returns true, and not if it returns false? You might get a bit frustrated if you try something like the following <form> tag:

  • <form method="post" onSubmit="ValidateForm()" action="EmailFormPost.asp" name="mailform">

This looks as if it should work, because ValidateForm() is a function, and we set the onSubmit equal to it. But actually, it doesn't work that way. Instead, you need to use the word "return" to actually feed the value back so it halts the submission if the function returns false. Here's the correct way to call the function:

  • <form method="post" onSubmit="return ValidateForm()" action="EmailFormPost.asp" name="mailform">

Go back