Validation

See more about:

Where are we?

You know how to grab data from text fields, and do things with it. But what if the user doesn’t type anything? Or says that his or her age is -15?

This lesson is about validation, that is, checking the data that the user typed.

This lesson’s goals

By the end of this lesson, you should:

  • Know how to check whether a field has a value.
  • Know how to check whether a number is OK.

Is something there?

Let’s start with this page:

Age

Figure 1. Age

If the user clicks the button without entering anything, this is what happens:

Age is empty

Figure 2. Age is empty

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 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(){
          age = $("#age").val();
          if ( age == "" ) {
            alert("Please enter your age.");
          }
        });
      });
    </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 3. Age checker

You can try it.

The action starts on line 18:

age = $("#age").val();
if ( age == "" ) {
  alert("Please enter your age.");
}

Part of Figure 3. Age checker

Line 18 gets the value that the user typed, and puts it into the variable age.

The next line has an if statement. This is what does the check. The general form of an if statement is:

if ( test ) {
  Do this if the test is true.
}

The test is a comparison that is either true or false. Here’s line 19 again:

if ( age == "" ) {

== is true if the thing on the left is the same as the thing on the right. The thing on the left contains the value the user typed. The thing on the right is an empty string. The quotes are jammed together, with nothing between them.

Important! == and = are not the same! == means “are they the same?” = means “put something into a variable.” This would fail:

if ( age = "" ) { //WRONG!

Exercise: Favorite animal

Write a page that looks like this:

Favorite animal

Figure 1. Favorite animal

If the user clicks the button without typing anything, show a message:

No favorite animal

Figure 2. No favorite animal

Upload your solution to your server and put the URL below.

(Log in to enter your solution to this exercise.)

true code and false code

You can also tell the browser what to do when the test is false:

if ( test ) {
  Do this if the test is true.
}
else {
  Do this if the test is false.
}

Let’s use this in the age checker.

age = $("#age").val();
if ( age == "" ) {
  alert("Please enter your age.");
}
else {
  alert("Thank you!");
}

Figure 4. Age checker junior

Exercise: Favorite animal again

Change your previous page so that it thanks the user if s/he puts something in the field. Like this:

Thank the user

Figure 1. Thank the user

Upload your solution and put the URL below.

(Log in to enter your solution to this exercise.)

You can include as many statements as you like between the braces of an if statement. For example, you could do this:

age = $("#age").val();
if ( age == "" ) {
  alert("Please enter your age.");
}
else {
  double_age = age*2;
  alert("In " + age + " years, you will be " + double_age + ".");
  alert("Last year, you were " + (age - 1) + ".");
}

Figure 5. Age checker III

You can try it.

Exercise: Favorite animal again, again

Change your favorite animal page. If the user enters nothing, it shows two messages. The first one should be:

First message

Figure 1. First message

When the user clicks the button, a second message shows:

First message

Figure 2. Second message

(Log in to enter your solution to this exercise.)

if this and if that

Often you want to chain if statements together. Here’s an example.

age = $("#age").val();
if ( age == "" ) {
  alert("Please enter your age.");
}
else if ( isNaN(age) ) {
  alert("Please enter a number.");
}
else if ( age < 21 ) {
  alert("Sorry, you are too young.");
}
else {
  alert("Thank you!");
}

Figure 6. Yet another age checker

Just one of the alert()s above will be shown. You can try it.

There are some other new things here. Here’s line 22:

else if ( isNaN(age) ) {

isNaN(age) is true if age is Not A Number. You have to get the name right when you type the function. So isnan, IsNaN, and isNAN are all incorrect.

Here’s line 25:

else if ( age < 21 ) {

This is true if age is less than 21.

Here are some other comparisons you can do:

== is equal to
!= is not equal to
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to

Figure 7. Comparison operators

You can check text strings as well. For example:

if ( age == "old" ) {
   alert("You don't look old.");
}

Exercise: Math quiz

Create a page that asks the user to answer a math question:

Math quiz

Figure 1. Math quiz

Show an alert() like this:

Math quiz response

Figure 2. Math quiz response

Here are the rules for the alert()s:

  • If the field is empty, show “Please enter your answer.”
  • If the field doesn’t contain a number, show “Please enter a number.”
  • If the field is less than 14, show “Sorry, that is too low.”
  • If the field is more than 14, show “Sorry, that is too high.”
  • If the field is 14, show “You got it right!.”

Upload your solution to your server, and put the URL below.

(Log in to enter your solution to this exercise.)

Summary

You know how to grab data from text fields, and do things with it. But what if the user doesn’t type anything? Or says that his or her age is -15?

In this lesson, you learn how to:

  • Check whether a field has a value.
  • Check whether a number is OK.

What now?

Wow! That was one of the most complicated lessons so far. But you will use the things you’ve learned again and again.


How to...

Lessons

User login

Log in problems? Try here


Dogs