One particularly useful application of value-returning functions is for validating user input. On forms, it's a good idea to verify that the information provided by the user is correct before processing it. For example, we might check that:
Here is the sample form that we will be working with in today's lecture. (View source to see the HTML code).
As a first example, let's validate that the name field in our form is not blank. First, we need to know how to reference the text field where the user types in her name. Here is the part of the form that defines the text fields:
<form name="easyform" ... > Please enter your name <input type="text" name="yourname"> Please enter your birth year <input type="text" size="5" name="birthyear"> ... other inputs here </form>
So, the contents of these two fields are
document.easyform.yourname.value document.easyform.birthyear.value
To validate the name field, we want to do something like this (the green text is just English descriptions — as opposed to JavaScript):
if (the name text box is blank ) { Show an alert with a reminder message Form is not done yet } else { Show a personalized thank you message Form is done }
| English | JavaScript |
|---|---|
|
the name text box is blank |
|
|
Show an alert with a reminder message |
|
|
Show a personalized thank you message |
|
|
Form is done |
|
|
Form is not done yet |
|
Translation:
<head>
<script type="text/JavaScript">
function checkName()
{
if (document.easyform.yourname.value == "") {
alert("argh! Please provide your name.");
return false;
} else {
alert("Thank you, "+ document.easyform.yourname.value + ".");
return true;
}
} /* checkName() */
</script>
</head>
The most important observation is this: We want
checkName() to be a boolean function that will
true if the name field is filled out, and
false if it is blank.
The default behavior of the SUBMIT button is to send the form's fields to the server when clicked. Its code is simply
<input type="submit"
value="Click Here to Submit"
onClick="return true;"
>
Note that the onClick attribute is optional if we want
the default behavior (ie, we want the form's action
performed). But this is not what we want here. We want
onClick="return true;"
if the yourname field is filled, and
onClick="return false;"
if the yourname field is empty.
So what we really want is something like
onClick="if (checkName() == true) {
return true; /* submit the form */
} else {
return false; /* don't submit the form */
}"
Notice that, because checkName() returns true or false exactly when we want, the preceding code is essentially equivalent to:
onClick="return checkName();"
Therefore, the full code for the SUBMIT button is:
<input type="submit"
value="Click Here to Submit"
onClick="return checkName();"
>
Here is what happens: When the user clicks the button, the
onClick script is executed. This says "return
checkName();". Therefore the function checkName() is
executed. When it finishes execution, it will return a boolean value,
either true or false. If
checkName() returns true, then the
onClick code will be equivalent to
onClick="return true;"
This will effectively let the submission of the form proceed. If, on
the other hand, checkName() returns false, then
the onClick code will be equivalent to
onClick="return false;"
and the submission of the form will be halted.
There is another place we can invoke checkName(): When a
form is submitted, another event called Submit is generated. This event
is associated with the form itself, not any particular button. One could
write a handler, via onSubmit, for the Submit event as
follows:
<form name = "easyform"
method = "post"
action = "http://cs.wellesley.edu/cgi-bin/eform.cgi"
onSubmit = "return checkName();" >
Now, after making these changes, when the user clicks on
the SUBMIT button on the form, the function
checkName() will be called and the name field
validated. ta-dah!
NOTE: You only need to call checkName() once,
either
onClick handler, or
onSubmit handler.
Not in both!
Here is the validated form to see it work. Experiment carefully with the form. You can view source on the form to see all the code. Is it behaving in the way that you expected? Why or why not?
Write a function called checkNameYear() that, in addition
to validating that the name field is filled out, also validates that the
birth year is 4 digits long. Hint: you may need to use a cascading
if in checkNameYear().
We know how to validate a text box (to check that it's not empty),
because we know that it has a value property, and we can
compare that value to the empty string to see whether the
text box has been filled out. How can we validate other kinds of inputs,
such as checkboxes?
How are the checkboxes named? Consider the following HTML code from our form:
Were you a ghost for halloween? Yes <input type="checkbox" name="ghost" value="YES" > No <input type="checkbox" name="ghost" value="NO" > It's a secret <input type="checkbox" name="ghost" value="Secret" >
They are all named the same (because logically they belong to the same group)!
How do we distinguish which is which? By counting them.
Computer Scientists start counting — ahem — from
zero. So:
document.easyform.ghost[0] is the "yes" box,
document.easyform.ghost[1] is the "no" box, and
document.easyform.ghost[2] is the "it's a secret" box.
How can we write a JavaScript expression to check if at least one of
the boxes has been checked? The key thing to know is that each checkbox
has a property called checked, which has a
boolean value: either true or false.
The checked property is true when the box
has a check in it, and it's false otherwise.
Using these new facts, let's see how to write the code. First, though,
let's figure out the logic of it. We want to check that at least one of
the boxes is checked. Equivalently, we want to complain and return
false if none of them are checked. None of them are
checked when the first one isn't checked and the second one isn't
checked and the third one isn't checked. Let's start writing
JavaScript, but with lots of English mixed in:
if (the first check box is not checked AND
the second checkbox is not checked AND
the third check box is not checked) {
show alert message
Not done yet
}
Since this will require combining boolean values, before we write the JavaScript code, let's remind ourselves of the two boolean combination operators:
&& means AND: true when both
conditions are true
|| means OR: true when either condition is
true
Now we're ready to write some JavaScript.
if ( (document.easyform.ghost[0].checked != true) &&
(document.easyform.ghost[1].checked != true) &&
(document.easyform.ghost[2].checked != true) ) {
alert("Please answer the ghost question.");
return false;
}
An improved version would be:
if ( !document.easyform.ghost[0].checked &&
!document.easyform.ghost[1].checked &&
!document.easyform.ghost[2].checked ) {
alert("Please answer the ghost question.");
return false;
}
Things to note:
if
in the validation function
Write a JavaScript expression to validate that not more than two of the
checkboxes were selected from easyform.
Write a JavaScript expression to validate that one and only one of the
checkboxes was selected from easyform.
Here is the part of our form that uses radio buttons:
You will graduate from Wellesley Class of:
<input type="radio" name = "graduation" value = "2008"> 2008 <input type="radio" name = "graduation" value = "2009"> 2009 <input type="radio" name = "graduation" value = "2010"> 2010 <input type="radio" name = "graduation" value = "2011"> 2011
How can we refer to radio button associated with 2009?
document.easyform.graduation[1]
Since users can only check one radio button, you can validate that a selection has indeed been made. Thus, the logic is that at least one has to be checked. Equivalently, complain if none of them has been checked. In other words, if the first one isn't checked, and the second one isn't checked, and ...
Write a JavaScript expression to validate that a graduation radio button was checked from easyform.
We've seen how to validate text boxes, check boxes and radio
buttons. What about pull-down menus? A pull-down menu has a property
named selectedIndex. It's value is the
number (starting, of course, from 0) of the menu item that was
selected. For example, if the
document.easyform.cartoon.selectedIndex is 0, the first menu
item was selected; if the
document.easyform.cartoon.selectedIndex is 1, the second item
was selected. Yes, it's confusing that they start the numbering at zero,
but you just have to be careful.
Here's how it works:
document.easyform.cartoon.selectedIndex
|
menu choice |
|---|---|
|
0 |
select one |
|
1 |
Bugs Bunny |
|
2 |
Mickey Mouse |
|
3 |
Yosemite Sam |
|
4 |
Betty Boop |
Fill in the appropriate alert messages and return values for the code
segment below (in the context of the easyform form).
if (document.easyform.cartoon.selectedIndex == 0) {
alert(" ");
return _________;
}
else {
alert(" ");
return _________;
}
The example form we worked with, above, had many inputs that could and should be validated. How do we put all these parts together into a completely validated form? The short answer is to combine them all with "and"; the long answer will take the rest of the lecture notes.
First, try the validated form with testing buttons. Fill out the form elements (or not) and click on the various testing buttons to see what they do, and how they change their behavior
Let's look at this code step by step.
true when the input is filled out and false
otherwise. Does it?
true, otherwise it won't.
function validName()
{
if (document.easyform.yourname.value != "") {
return true;
} else {
alert("please fill out the name field");
return false;
}
}
The other validation functions work the same way. What's nice about making each its own function is that you can test them individually, and that's really helpful in narrowing down where the bug is when you have a complex form with many inputs to validate. This follows from modularity, which is one of the big ideas in computer science.
Now, the leap to validating more than one input is just to combine
them, logically. The form is valid if all of those
individual validation functions returns true.
Specifically, the form is valid if
The JavaScript logical operator that means and is
&&. That's why the function for validating the whole
form is:
function validForm()
{
if ( validName()
&& validBirthYear()
&& validGhost()
&& validClass()
&& validCartoon() ) {
alert("Thanks for filling out the form!");
return true;
} else {
return false;
}
}
Test that out and see whether it works and makes sense.
Is it okay to submit this form?
true or
false from:
onSubmit event handler of the FORM tag
onClick event handler of the INPUT
TYPE="SUBMIT" button
true or
false
true or false
© Computer Science 110 Staff
This work is licensed under a Creative Commons License
Date Modified:
Thursday, 24-Jan-2008 14:36:29 EST