HTML and CSS Reference
In-Depth Information
Task:
Exercise 15.1: Form Validation
▼
Now take a look at how the registration form is validated with JavaScript. Whenever you
click the Submit button on a form, two events are triggered: the
onclick
event for the
button and the
onsubmit
button for the form. For form validation,
onsubmit
is the better
choice, because some forms can be submitted without clicking the Submit button. When
the
onsubmit
event is fired, the validation function will be called.
15
The
onsubmit
attribute is set in the
<form>
tag, like this:
<form method=”post”
action=”http://www.example.com/register”
onsubmit=”return checkform(this)”>
In this example, the value assigned to
onsubmit
is a call to a function named
checkform()
—which is defined in the page header. But first, the
return
statement
at the beginning of the
onsubmit
field and the
this
argument inside the parentheses
in the
checkform()
function need some further explanation.
As you might remember from the preceding lesson, the argument to the
checkform()
function,
this
, has a special meaning. In the context of an event handler, it is a reference
to the tag that the event handler is associated with. So in this case, when
checkform()
is
called, I pass it a reference to the form, from which I can access all the form fields that I
want to validate. The
onsubmit
handler can accept a return value. If the return value is
false, then the action is canceled. If it is true, then the form submission continues.
So by including the return statement in the event handler, I pass the return value of
checkform()
to the event handler, enabling me to stop the form from being submitted if
the values in the form are invalid.
The Validation Function
In a
<script>
tag inside the
<head>
block, you will be
declaring the
checkform()
function. . The function accepts a single parameter, which
you'll name
thisform
. It is a reference to the form that will be validated. The code for
the function declaration looks like this:
<script language=”JavaScript”>
function checkform(thisform) {
// Validation code
return true;
}
</script>
I went ahead and stuck
return true
in the function. If there are no invalid fields, the
form submission should be successful.