Simple Form Validation with the return Keyword
Here we are performing simple validation to make sure the user entered something into the text field. This is a very common use for JavaScript - checking form element values before sending information to the server, saving bandwidth, server CPU cycles and mostly importantly, the user's time.
The function uses a simple if/else clause to check whether or not anything was entered into the form field. If nothing has been entered, we alert the user and
return a value of false to where the function is being called -
in the onSubmit event handler of the form tag. Then the onSubmit event handler returns that same value to the browser because the function call is preceded by another return keyword.
Remember - when the return keyword is used in the body of a function, a value is returned back to where the function is being called. When the return keyword is used in an event handler, a value is returned to the browser.
function checkEntry() {
var name = document.whatIs.yourName.value
if(name == ""){ //if field is left empty
alert("Please enter your name")
return false // return false value to onSubmit handler
}
else {
alert("Thank you for entering your name, " + name)
return true
}
}
The return keyword preceding the call to the function is what determines if the form should indeed be submitted. If a value of true is returned to the onSubmit event handler via the checkEntry() function, a submission will occur. If a value of false is returned, the submission is cancelled.
<form name="whatIs" onSubmit="return checkEntry()"> //here, checkEntry() can be read as either true or false
<input type="text" name="yourName">
<input type="submit">
</form>
NOTE: Although we're not actually sending anything to the server (an action is not specified in the form tag), we are using a 'real' submit button (<input type="submit">). Submit buttons cause a form to be submitted, while input type button elements do not.
You can also submit a form by pressing the Enter/Return key from within an input type text field if it is the only text field in the form.
If you do not need your form to actually submit when a submit button is clicked, or want to safeguard against users submitting via the enter/return key, always return false following the function call in the onsubmit event handler of your form tag.
<form onsubmit="myfunction(); return false">
This causes the function to be invoked via a submit button click or enter/return key press, but stops the form from submitting. Preceding the function call with the return keyword will also work, as long as your function is returning a value of true or false.
See
Submitting Forms by Detecting Carriage Return / Enter Key Presses for more information on forcing and suppressing form submission with enter key press.
For a very robust form validation script, see
Form Validation on Steroids.
For a smaller, simpler form validation script, see
Form Validation on Steroids.
View the Source