๐Ÿงช Interactive lesson ยท Grades 9 and 10 ยท about 45 minutes

Checking forms with JavaScript

Teach your page to stop believing everything! Read the boxes, test them with if, answer in red and green, use the browser's own rules, add a timer and a random number, then build the Mystery Box game. Every example is a real page you can change and run.

Grades 9 and 10Real pages you can run8-step Mystery BoxQuiz and projectFree ยท no sign-up

A complete lesson ยท 45 minutes

Check first, then believe it.

Open this page with your learner and work down it. Every dark box is a real web page: change the code, press โ–ถ Run, and see what happens.

By the end you can

  • say what form validation is and why pages need it
  • read what was typed with getElementById and .value
  • write checks with if and an ok flag
  • show messages with textContent and style.color
  • use type, min, max, required and checkValidity()
  • add a timer and a random number

Before you start

  • Basic HTML: input, button and p
  • Variables and functions in JavaScript

Have ready

  • This page (nothing to install)
  • A notebook for the six rules

Warm-up ยท think first

The form that believes everything

Press Join with both boxes empty. Then type abc as your age and press it again. The page welcomes anyone with anything. By the end of this lesson it will check first.

Try it
Your pageruns for real

Part 1

What form validation is

Validation means checking what someone typed before the page uses it. A sign-up page should not welcome a person with no name, and a quiz should not accept 500 as an answer between 1 and 10. The check happens in a function that runs when the button is pressed: read each box, test it, and only carry on when everything passes.

๐Ÿ’ญ Think of it this way

A cinema ticket checker looks at every ticket before anyone goes in. No ticket, wrong film or wrong time: you wait outside and they tell you why. Validation is the ticket checker for your page.

๐Ÿ“Œ Remember

Check first, then act. The function that runs on the button does the checking at the top and the real work only at the end.

Part 2

Reading what was typed: .value

Every box you want to read needs an id. document.getElementById("pet") finds the box; .value gives you what is typed in it, right now. Store it in a variable so you can test it and use it.

Try it: Type a name and press Show. Then open the console under the preview: it says what was typed and its type.

Try it
Your pageruns for real
๐Ÿ’ญ Think of it this way

Each box is a labelled drawer. getElementById reads the label and opens the right drawer; .value is the note lying inside it.

๐Ÿ“Œ Remember

.value is always text (a string), even in a number box. "7" + 1 gives "71". Use Number(...) when you need to do maths with it.

Part 3

Writing the checks: if and the ok flag

Each rule is an if. An empty box gives an empty string, so name === "" catches it (trim() first removes spaces, so a name of only spaces counts as empty). For a number, check that the box is not empty, then that the number is in range. Keep one true/false variable, ok, that starts as true; any failed rule makes it false.

Try it: Press Check with empty boxes, then with age 20, then with a name and age 12.

Try it
Your pageruns for real
๐Ÿ’ญ Think of it this way

Think of a teacher's tick. Every paper starts with โœ“. Each mistake turns it into โœ—. At the end, only papers still showing โœ“ go on the wall.

๐Ÿ“Œ Remember

Set ok = true before the checks, only ever set it to false inside them, and decide what to do after all of them have run.

Part 4

Telling the user: messages and colours

Good forms answer straight away and say exactly what to fix. Put an empty paragraph under each box for its message, then change it from JavaScript: textContent for the words, style.color for the colour. Red for a problem, green when it is fixed.

Try it: Type two letters and press Check, then type a longer nickname and check again. Change the colours or the minimum length and press Run.

Try it
Your pageruns for real
๐Ÿ’ญ Think of it this way

It works like a traffic light beside each box: red means stop and fix this one, green means this one is fine.

๐Ÿ“Œ Remember

A message must say how to fix the problem ("Use at least 3 letters"), not only that something is wrong. And clear it, or turn it green, once it is fixed.

Part 5

Rules the browser knows: type, min, max, required

HTML can carry rules too. type="number" only takes numbers, min and max set the range, required means it must not be empty, maxlength limits how many letters. The browser checks these when a form is sent, and you can ask it yourself: box.checkValidity() gives true or false, and box.validationMessage is the browser's own explanation.

Try it: Press Test with the box empty, with 15, and with 7.

Try it
Your pageruns for real
๐Ÿ’ญ Think of it this way

The HTML rules are the fence around the playground; your JavaScript checks are the teacher on duty. The fence stops most problems, the teacher handles the rest.

๐Ÿ“Œ Remember

HTML rules are a first fence, not the only one: keep your JavaScript checks too. (Real websites check a third time on their server, because anyone can change the HTML in their own browser.)

Part 6

Timers and random numbers

setInterval(function () { ... }, 1000) runs the code inside again and again, every 1000 milliseconds (one second): perfect for a clock on the page. Math.random() gives a number from 0 up to (not including) 1. Times 6 gives 0 up to 5.99โ€ฆ; Math.floor cuts off the decimals, giving 0 to 5; plus 1 gives a whole number from 1 to 6, like a dice.

Try it: Watch the clock count, and roll a few times. Then change 6 to 20 and press Run: a 20-sided dice.

Try it
Your pageruns for real
๐Ÿ’ญ Think of it this way

setInterval is a kitchen timer that rings every second, and each time it rings it does the job you gave it. Math.random is a hand pulling one ticket out of a hat.

๐Ÿ“Œ Remember

Math.floor(Math.random() * N) + 1 gives a whole number from 1 to N. The timer's 1000 is in milliseconds.

Activity ยท about 15 minutes

๐ŸŽ Build the Mystery Box

Five boxes, one hidden prize. The player types their name and picks a box from 1 to 5. Your page checks both answers, hides the prize in a random box, says whether they found it, and shows how long they have been playing. Build it in eight steps: type each step into the editor and press Run after every one.

  1. The name boxAdd the heading, a line telling the player what to do, a text box with id="name", and an empty paragraph under it with id="msg-name" for its message.
    Stuck? See the code for step 1
    <h1>๐ŸŽ Mystery Box</h1>
    <p>Five boxes, one prize. Type your name and pick a box!</p>
    
    <input type="text" id="name" placeholder="Your name" required>
    <p id="msg-name"></p>
  2. The box-number boxAdd a number box with id="box" that only allows 1 to 5 (type, min, max, required), and its message paragraph with id="msg-box".
    Stuck? See the code for step 2
    <input type="number" id="box" placeholder="Box number (1 to 5)" min="1" max="5" required>
    <p id="msg-box"></p>
  3. The button, the result and the timerAdd a button that calls openBox() when clicked, then two empty paragraphs: id="result" and id="timer".
    Stuck? See the code for step 3
    <button onclick="openBox()">Open my box!</button>
    <p id="result"></p>
    <p id="timer"></p>
  4. Read the boxesInside the script, write the openBox function. Read both boxes with getElementById and .value, and start an ok flag at true.
    Stuck? See the code for step 4
    function openBox() {
      var name = document.getElementById("name").value.trim();
      var boxText = document.getElementById("box").value;
      var box = Number(boxText);
      var ok = true;
    
      // step 5, step 6 and step 7 go here
    }
  5. Check the nameIf the name is empty: a red message under the name box and ok = false. Otherwise a green "Hi, โ€ฆ!".
    Stuck? See the code for step 5
      var msgName = document.getElementById("msg-name");
      if (name === "") {
        msgName.textContent = "Please type your name first.";
        msgName.style.color = "crimson";
        ok = false;
      } else {
        msgName.textContent = "Hi, " + name + "!";
        msgName.style.color = "green";
      }
  6. Check the box numberEmpty, below 1 or above 5: a red message and ok = false. Otherwise green.
    Stuck? See the code for step 6
      var msgBox = document.getElementById("msg-box");
      if (boxText === "" || box < 1 || box > 5) {
        msgBox.textContent = "Pick a box from 1 to 5.";
        msgBox.style.color = "crimson";
        ok = false;
      } else {
        msgBox.textContent = "Box " + box + " it is!";
        msgBox.style.color = "green";
      }
  7. Hide the prize and open the boxOnly if ok is still true: pick the prize box with Math.random, then say whether the player found it.
    Stuck? See the code for step 7
      var result = document.getElementById("result");
      if (ok) {
        var prize = Math.floor(Math.random() * 5) + 1;
        if (box === prize) {
          result.textContent = "๐ŸŽ‰ " + name + ", box " + box + " had the prize!";
          result.style.color = "green";
        } else {
          result.textContent = "Empty! The prize was in box " + prize + ". Try again!";
          result.style.color = "crimson";
        }
      } else {
        result.textContent = "";
      }
  8. The timerBelow the function (not inside it), count the seconds the player has been on the page with setInterval and show them in the timer paragraph.
    Stuck? See the code for step 8
    var seconds = 0;
    setInterval(function () {
      seconds = seconds + 1;
      document.getElementById("timer").textContent = "You have been playing for " + seconds + " seconds.";
    }, 1000);
Your Mystery Box
Your pageruns for real
๐Ÿ The finished game (open it after you have tried)
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: Arial, sans-serif; background: #fff8e7; text-align: center; padding: 20px; }
  h1 { color: #7a3e00; }
  input { padding: 8px; margin: 4px; border: 2px solid #7a3e00; border-radius: 8px; width: 210px; }
  button { background: #7a3e00; color: white; padding: 10px 22px; border: none; border-radius: 20px; cursor: pointer; }
  #timer { color: grey; }
</style>
</head>
<body>

<h1>๐ŸŽ Mystery Box</h1>
<p>Five boxes, one prize. Type your name and pick a box!</p>

<input type="text" id="name" placeholder="Your name" required>
<p id="msg-name"></p>

<input type="number" id="box" placeholder="Box number (1 to 5)" min="1" max="5" required>
<p id="msg-box"></p>

<button onclick="openBox()">Open my box!</button>
<p id="result"></p>
<p id="timer"></p>

<script>
function openBox() {
  var name = document.getElementById("name").value.trim();
  var boxText = document.getElementById("box").value;
  var box = Number(boxText);
  var ok = true;

  var msgName = document.getElementById("msg-name");
  if (name === "") {
    msgName.textContent = "Please type your name first.";
    msgName.style.color = "crimson";
    ok = false;
  } else {
    msgName.textContent = "Hi, " + name + "!";
    msgName.style.color = "green";
  }

  var msgBox = document.getElementById("msg-box");
  if (boxText === "" || box < 1 || box > 5) {
    msgBox.textContent = "Pick a box from 1 to 5.";
    msgBox.style.color = "crimson";
    ok = false;
  } else {
    msgBox.textContent = "Box " + box + " it is!";
    msgBox.style.color = "green";
  }

  var result = document.getElementById("result");
  if (ok) {
    var prize = Math.floor(Math.random() * 5) + 1;
    if (box === prize) {
      result.textContent = "๐ŸŽ‰ " + name + ", box " + box + " had the prize!";
      result.style.color = "green";
    } else {
      result.textContent = "Empty! The prize was in box " + prize + ". Try again!";
      result.style.color = "crimson";
    }
  } else {
    result.textContent = "";
  }
}

var seconds = 0;
setInterval(function () {
  seconds = seconds + 1;
  document.getElementById("timer").textContent = "You have been playing for " + seconds + " seconds.";
}, 1000);
</script>

</body>
</html>

Wrap-up

Six rules to remember

  1. Give every box an id, and read it with document.getElementById("id").value.
  2. .value is text: compare with "" for empty, and use Number(...) for maths and ranges.
  3. Start ok = true, set it to false when a rule fails, and act only if it is still true at the end.
  4. Tell the user what to fix, next to the box, in red; turn it green when it is fixed.
  5. HTML rules (type, min, max, required) help, but keep your JavaScript checks.
  6. Math.floor(Math.random() * N) + 1 is a whole number from 1 to N; setInterval(fn, 1000) runs fn every second.

Quiz

Five quick questions

1The box is empty. What does document.getElementById("name").value give?

2The age box shows 7. What is document.getElementById("age").value + 1?

3Which line gives a whole number from 1 to 10?

4setInterval(tick, 2000) runs tickโ€ฆ

5Three rules are checked with an ok flag. The second one fails. What is ok at the end?

After class

Project: the Coding Club sign-up

Make a sign-up form that checks three boxes: a username of at least 3 letters, an age from 10 to 15, and a password of at least 6 characters. Each box gets its own red or green message, and the welcome appears only when all three pass. Extra: show how many seconds the sign-up took, and give each new member a random badge number from 1 to 100.

Coding Club sign-up
Your pageruns for real

For teachers

The 45-minute plan

Show the minute-by-minute plan
MinutesWhatHow
0โ€“3Warm-upOpen the Space Club form. Ask them to press Join with empty boxes, then type "abc" as the age. "What should the page have said?"
3โ€“81 and 2: validation, .valueThe ticket checker. Type a pet's name and read the console: the type is string. Ask: what is "7" + 1?
8โ€“153: the checksBuild the ok flag together. Try empty, age 20, then a good answer. Let them predict each message before pressing.
15โ€“194 and 5: feedback and HTML rulesRed and green messages. Then checkValidity(): empty, 15 and 7. Say why JavaScript checks stay.
19โ€“226: timers and randomThe clock counts by itself. Roll the dice, then change 6 to 20 together.
22โ€“38Activity: Mystery BoxEight steps; they type, you guide. Open the step's code only when they are stuck. Run after every step.
38โ€“42Rules and quizRead the six rules aloud, then the five questions. Ask why for each answer.
42โ€“45After-class projectShow the Coding Club sign-up starter and agree when it is due.

In a 60-minute group class, give the activity 25 minutes and let students compare their Mystery Boxes before the quiz.

Play it, don't just read it

Take a break and play

Free games that need no sign-up. Pick one and play for five minutes.

All free games โ†’
Chat on WhatsApp
Esc

Try