Client-side validation
Where are we?
In a Web application, data validation takes place on the browser and on the server. You learned how to some validation with JavaScript in a ClientCore lesson.
This lesson reminds you how to do validation in JavaScript. It also tells you how to do better error reporting.
This lesson’s goals
By the end of this lesson, you should:
- Know how to get form data into JavaScript variables.
- Be able to check that data for errors.
- Report errors to the user.
A JavaScript and jQuery review
Let’s review some JavaScript and jQuery. Let’s start with a page like this:

Figure 1. Empty form
Notice that the input focus is on the first field; you can tell because the cursor is there.
The user completes the field clicks the Go button. Here is the result.

Figure 2. Complete form
The output area only appears after the button is clicked. It appears with an animated effect.
You can try the page.
Here is the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Review</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body {
font-family: Verdana, sans-serif;
font-size: 14px;
background-color: #FFFFE0;
}
/* Output area starts out hidden. */
#output_area {
display: none;
}
/* Used to highlight the user's name. */
.highlight {
font-weight: bold;
color: red;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//Put the input focus in the first field.
$("#first_name").focus();
//Set up the button click.
$("#go").click(function(){
//Get the input.
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
//Compute the full name.
var full_name = first_name + ' ' + last_name;
//Show output.
$("#full_name")
.text(full_name)
.addClass('highlight');
$("#output_area").show('medium');
});
});
</script>
</head>
<body>
<h1>Review</h1>
<p>
First name:
<input type="text" id="first_name" size="20">
</p>
<p>
Last name:
<input type="text" id="last_name" size="20">
</p>
<p>
<button type="button" id="go">Go</button>
</p>
<div id="output_area">
<p>Your full name is <span id="full_name"></span>.</p>
</div>
</body>
</html>
Figure 3. Code for the page
Line 23 loads the jQuery library, from one of Google’s fast servers.
Line 25 starts the JavaScript. The line is:
$(document).ready(function() {
The code in the ready() function runs when the page has loaded.
Line 27:
$("#first_name").focus();
sets the input focus on to the HTML element with the id of first_name. That element is:
<input type="text" id="first_name" size="20">
That’s how the input focus appears in the first name field when the page first appears.
The field has an id attribute so that jQuery can reference the fields. But it doesn’t have a name attribute. name is used when sending data to a server. We’re not doing that here, so no name attribute is needed.
There is no <form> tag around the <input> elements. It’s only needed when data is being sent to a server, which we aren’t doing.
This line (number 29):
$("#go").click(function(){
attaches some code to the button’s click event. The code runs when the user clicks the button.
The tag for the button says type="button". The forms we’ve seen recently have used type="submit". A submit button is only used when send (submitting) data to a server. We’re not doing that, so type="button" makes more sense.
What do we want to happen when the user clicks the button? Here’s some pseudocode.
Get the first and last name the user typed. Put them together to make the full name. Show the full name.
Figure 4. click pseudocode
It’s a good idea to write pseudocode for every function you create. This helps:
- Be clear about the goal of the function, that is, what it does.
- Plan the code, without getting bogged down in the syntax details.
Here’s the JavaScript:
//Get the input.
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
//Compute the full name.
var full_name = first_name + ' ' + last_name;
//Show output.
$("#full_name")
.text(full_name)
.addClass('highlight');
$("#output_area").show('medium');
Figure 5. click code
Let’s see how this achieves the steps given in the pseudocode (Figure 4).
The first step in the pseudocode is:
Get the first and last name the user typed.
I added a comment in line 30, explaining what the code is doing.
Line 31 gets the value the user typed into the first_name field, and puts it into the JavaScript variable first_name:
var first_name = $("#first_name").val();
The names of the field and the variable don’t have to be the same, but it makes the code easier to understand. Line 32 gets the last name.
That’s the first step in the pseudocode: get the user input.
The second step in the pseudocode (Figure 4) is:
Put them together to make the full name.
Line 34 takes the first name, appends a space to it, and then appends the last name. The result gets put into the variable full_name:
var full_name = first_name + ' ' + last_name;
The third step in the pseudocode (Figure 4) is:
Show the full name.
Line 36 finds an element with an id of full_name:
$("#full_name")
That element is the <span>:
<p>Your full name is <span id="full_name"></span>.</p>
Next, set the text of that element to the contents of the variablefull_name:
$("#full_name")
.text(full_name)
Then add the class highlight to the element:
$("#full_name")
.text(full_name)
.addClass('highlight');
The class is defined in the CSS as:
.highlight {
font-weight: bold;
color: red;
}
Lines 36 to 38 use method chaining (“method” is a type of function). The statement could have been typed all on one line, like this:
$("#full_name").text(full_name).addClass('highlight');
Spreading across three lines makes it easier to read.
Line 39 is:
$("#output_area").show('medium');
It makes the element with the id of output_area appear. It uses an animated effect at medium speed.
Let’s look at the structure of the output area again, just to be sure what is going on.
<div id="output_area"> <p>Your full name is <span id="full_name"></span>.</p> </div>
Part of Figure 3 (again). Code for the page
output_area is a container for, well, the output area. Inside it are places for the individual output pieces. There is only one in this example: full_name. But there could be more.
This is a common pattern.
Create a container for the output. Have individual output elements inside the container. Fill in the individual output elements. Show the entire output container at once.
Figure 6. Pattern for output with HTML and JavaScript
You can try the page.
Exercise: Your favorite animals
Create a page that looks like this when first displayed:

Figure 1. Empty form
Notice that the input focus is in the first field.
When the user fills in the form and clicks the button:

Figure 2. Form with data
You can try my solution to see how it works. But don’t look at the source code until you try it yourself first!
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Checking numbers
Let’s see how you can use JavaScript to check the data that users type into form fields. Start with this one:

Figure 6. Age check form
The user types something in the field, and clicks the button. Some JavaScript checks the value, and shows a message, like this:

Figure 7. Age error
You can try it.
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Check age 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body {
font-family: Verdana, sans-serif;
font-size: 14px;
background-color: #FFFFE0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#age").focus();
$("#go").click(function(){
var age = $("#age").val();
if ( age == "" ) {
alert("Sorry, please enter your age.");
}
else if ( isNaN(age) ) {
alert("Sorry, please enter a number.");
}
else if ( age < 0 || age > 120 ) {
alert("Sorry, please enter a valid age.");
}
else if ( age < 21 ) {
alert("Sorry, you are too young.");
}
else {
alert("Thanks! You can proceed.");
}
$("#age").focus();
});
});
</script>
</head>
<body>
<h1>Check age 1</h1>
<p>
Age:
<input type="text" id="age" size="3">
</p>
<p>
<button type="button" id="go">Go</button>
</p>
</body>
</html>
Figure 8. Code for age error check
Line 18 put the value the user typed into the variable age.
var age = $("#age").val();
Here is the first check:
if ( age == "" ) {
This is true if the variable is an empty string. Remember:
- Use
==and not=.
""is an empty string. The quotes are together with no space between them. This is not the same as" ", which is a string with a space in it.
Line 22 is:
else if ( isNaN(age) ) {
The isNaN() function returns true if the parameter is Not a Number.
This (line 25):
else if ( age < 0 || age > 120 ) {
means “if age is less than 0 or greater than 120.” || means “or,” && means “and,” and ! means “not.”
Here’s another example.
width > 10 && width < 50
widthis more than 10 and less than 50. Note that leaving out the secondwidthwill not work:
width > 10 && < 50
Some more.
x < 10 || y == 10
xis less than 10, oryis equal to 10. You can have as many different variables as you want in aniftest.
(x + y) < 100 && z != 11
xplusyis less than 100, andzdoes not equal 11. You can do computations like this inifstatements.
Exercise: Check song time
Create a page that looks like this when first displayed:

Figure 1. Empty form
Notice that the input focus is in the first field.
When the user clicks the button, JavaScript code checks the values in the fields. Each field must have a valid number. Minutes must be from 0 to 120. Seconds must be from 0 to 59.
Here’s an error message:

Figure 2. Error
If the data is OK, show this:

Figure 3. Data OK
You can try my solution to see how it works. But don’t look at the source code until you try it yourself first!
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Checking strings
Time to see how you can check strings. Here’s a log in form.

Figure 9. Empty log in form
Here’s an error message showing.

Figure 10. Log in error
Here’s the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Check log in 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body {
font-family: Verdana, sans-serif;
font-size: 14px;
background-color: #FFFFE0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#user_name").focus();
$("#login").click(function(){
var user_name = $("#user_name").val();
var password = $("#password").val();
if ( user_name == "" || password == "" ) {
alert("Sorry, you must enter both your user name and password.");
}
else if ( user_name.length < 6 ) {
alert("Sorry, the user name is too short.");
}
else if ( password.length < 6 ) {
alert("Sorry, the password is too short.");
}
else if ( user_name.toLowerCase() == "renata" ) {
alert("Sorry, Renata! You need to get permission.");
}
else {
alert("Thanks! You can proceed.");
}
$("#user_name").focus();
});
});
</script>
</head>
<body>
<h1>Check log in 1</h1>
<p>
User name:
<input type="text" id="user_name" size="20">
</p>
<p>
Password:
<input type="password" id="password" size="20">
</p>
<p>
<button type="button" id="login">Login</button>
</p>
</body>
</html>
Figure 11. Log in code
Line 48 has something new:
<input type="password" id="password" size="20">
A field with a type of password is just like a regular text field, except that it hides what the user types.

Figure 12. Password field in action
I gave the field an id of password. It could have been anything, but this id makes sense.
Lines 18 and 19:
var user_name = $("#user_name").val();
var password = $("#password").val();
get the values the user typed into the form.
This (line 20):
if ( user_name "" || password "" ) {
checks whether user_name or password are empty.
Here’s line 23:
else if ( user_name.length < 6 ) {
user_name.length returns the number of characters in a string.
Here’s line 29:
else if ( user_name.toLowerCase() == "renata" ) {
user_name.toLowerCase() returns a string user_name, but with all of the characters converted to lower case. So the if statement will succeed if the user enters renata, Renata, RENATA, renatA, etc.
This does not change the value of user_name. If we wanted to do that, we could write:
user_name = user_name.toLowerCase();
Exercise: New dog name
Create a page that looks like this when first displayed:

Figure 1. Empty form
Notice that the input focus is in the first field.
When the user clicks the button, JavaScript code checks the value in the field. The field cannot be empty. It must contain a value that is longer than one character, and shorter than 21 characters.
Here’s an error message:

Figure 2. Error
If the data is OK, show this:

Figure 3. Data OK
Hint: this combines the error checking in this section with the output method we saw earlier – showing an output container.
You can try my solution to see how it works. But don’t look at the source code until you try it yourself first!
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Reporting errors
So far, we have used simple alert() statements to report errors. But we can do better.
Let’s change the age page. The new page starts off like this:

Figure 13. Empty form
When there is an error, a message appears in the content of the page, right below the field the message is about. Like this:

Figure 14. Showing an error
Try the page. You’ll see that the error message appears with an animated effect.
Here is the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Check age 2</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
body {
font-family: Verdana, sans-serif;
font-size: 14px;
background-color: #FFFFE0;
}
#error_message {
font-weight: bold;
color: red;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#age").focus();
$("#error_message").hide();
$("#go").click(function(){
var age = $("#age").val();
if ( age == "" ) {
$("#error_message").text("Sorry, please enter your age.");
$("#error_message").show('medium');
}
else if ( isNaN(age) ) {
$("#error_message").text("Sorry, please enter a number.");
$("#error_message").show('medium');
}
else if ( age < 0 || age > 120 ) {
$("#error_message").text("Sorry, please enter a valid age.");
$("#error_message").show('medium');
}
else if ( age < 21 ) {
$("#error_message").text("Sorry, you are too young.");
$("#error_message").show('medium');
}
else {
$("#error_message").hide();
$("#ok_message").text("Thanks! You can proceed.");
}
$("#age").focus();
});
});
</script>
</head>
<body>
<h1>Check age 2</h1>
<p>
Age:
<input type="text" id="age" size="3"><br>
<span id="error_message"/>
</p>
<p>
<button type="button" id="go">Go</button>
</p>
<p id="ok_message"/>
</body>
</html>
Figure 15. Code for improved error reporting
Let’s look at the HTML first. There’s a place for an error message after the input field (see line 53):
<input type="text" id="age" size="3"><br>
<span id="error_message"/>
The span will show an error message when there is one.
Note that you can use <span id="error_message"/> as a shortcut for <span id="error_message"></span>, when the tag is empty.
The error message is hidden when the page loads:
$(document).ready(function() {
...
$("#error_message").hide();
error_message is highlighted by some CSS (lines 12 to 15).
#error_message {
font-weight: bold;
color: red;
}
If there is an error, some text is put into error_message, and it is shown. Here are lines 25 and 26:
$("#error_message").text("Sorry, please enter your age.");
$("#error_message").show('medium');
All of the errors are handled the same way. For example:
$("#error_message").text("Sorry, please enter a number.");
$("#error_message").show('medium');
What if there is no error? Here’s what happens (line 41):
$("#error_message").hide();
$("#ok_message").text("Thanks! You can proceed.");
This hides whatever error message was showing (if any). Then an “OK” message shows in a different place.
Exercise: New dog name, again
Create a page that looks like this when first displayed:

Figure 1. Empty form
Notice that the input focus is in the first field.
When the user clicks the button, JavaScript code checks the value in the field. The field cannot be empty. It must contain a value that is longer than one character, and shorter than 21 characters.
Here’s an error message:

Figure 2. Error
If the data is OK, show this:

Figure 3. Data OK
You can try my solution to see how it works. But don’t look at the source code until you try it yourself first!
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
Using a function
Have another look at the error checking code.
var age = $("#age").val();
if ( age == "" ) {
$("#error_message").text("Sorry, please enter your age.");
$("#error_message").show('medium');
}
else if ( isNaN(age) ) {
$("#error_message").text("Sorry, please enter a number.");
$("#error_message").show('medium');
}
else if ( age < 0 || age > 120 ) {
$("#error_message").text("Sorry, please enter a valid age.");
$("#error_message").show('medium');
}
else if ( age < 21 ) {
$("#error_message").text("Sorry, you are too young.");
$("#error_message").show('medium');
}
else {
Part of Figure 15 (again). Code for improved error reporting
There’s a lot of repeated code:
$("#error_message").text(A message);
$("#error_message").show('medium');
It would be better to create a function. Here’s the new code:
var age = $("#age").val();
if ( age == "" ) {
show_error("Sorry, please enter your age.");
}
else if ( isNaN(age) ) {
show_error("Sorry, please enter a number.");
}
else if ( age < 0 || age > 120 ) {
show_error("Sorry, please enter a valid age.");
}
else if ( age < 21 ) {
show_error("Sorry, you are too young.");
}
else {
...
//Show an error message.
function show_error(message) {
$("#error_message").text(message);
$("#error_message").show('medium');
}
Figure 16. Error function
This moves the repeated code into a function. Whatever message you send to the function will show in error_message. For example:
show_error("Sorry, you have fleas.");
show_error("Sorry, your " + toy_name + " is broken.");
The main advantage of this is that we can change the error processing all at once. For example, suppose we want to change the animation speed of all the error messages. So we want:
$("#error_message").show('medium');
to be:
$("#error_message").show('slow');
In Figure 15, we have several lines to change. It would be easy to miss one.
But with the function, we just change medium to slow on one line:
function show_error(message) {
$("#error_message").text(message);
$("#error_message").show('slow');
}
Functions give us another productivity win when changing a page.
Exercise: New dog name, once more with functions
Create a page that looks like this when first displayed:

Figure 1. Empty form
Notice that the input focus is in the first field.
When the user clicks the button, JavaScript code checks the value in the field. The field cannot be empty. It must contain a value that is longer than one character, and shorter than 21 characters.
Here’s an error message:

Figure 2. Error
Use a function to show error messages. Call the same function for every error message.
If the data is OK, show this:

Figure 3. Data OK
You can try my solution to see how it works. But don’t look at the source code until you try it yourself first!
Upload your solution to your server. Put the URL below.
(Log in to enter your solution to this exercise.)
- Less code to change.
- Less chance of making a mistake.
W00f!
Summary
In this lesson, you learned:
- How to get form data into JavaScript variables.
- How to check that data for errors.
- How to report errors to the user.
What now?
This lesson looked at client-side validation. Let’s start learning about server-side validation.




