The Academy

Loading the search index…

Searches the academy on this device only.

Validation, error handling and browser developer tools

Check what people type into a form, handle failures with try/catch, and use the browser's developer tools to find out why a page is not behaving.

35 minelementaryPractical task needs a laptop or desktop

Marking a lesson as read does not prove you can do it. Skills count as demonstrated when you pass the quiz (not yet) and complete the practical tasks (not yet).

By the end of this lesson you will be able to

  • Write a function that checks form input and shows a clear message.
  • Use try/catch to stop an error from breaking the whole script.
  • Open the developer tools and name the Elements, Console and Network panels.
  • Read a console error and find the file and line it points to.
  • Explain why validation in the browser is a convenience, not security.

People make mistakes in forms: an empty name, an email with no at sign, an age typed as words. Your code will also make mistakes, and sometimes a file will fail to load. A beginner who can check input politely and read the browser's own error reports can fix most problems alone, without waiting for anyone to help. This lesson gives you both skills, using tools already built into your browser.

Validating form input

Validation means checking that data is acceptable before using it. On a web form you do it so people get quick, kind feedback: "Please enter your name" appears at once instead of after a slow round trip to a server. The pattern is always the same: read the value, test it, and either show a message or carry on.

HTML can already do some checking with no JavaScript at all. Attributes such as required, type="email", minlength and min and max on numbers make the browser block submission and show its own message. Use those first, then add JavaScript for rules HTML cannot express, such as "the two passwords must match" or a friendlier message.

HTML
<form id="signup" novalidate>
  <label for="name">Name</label>
  <input id="name" name="name" type="text">

  <label for="email">Email</label>
  <input id="email" name="email" type="email">

  <label for="age">Age</label>
  <input id="age" name="age" type="number">

  <button type="submit">Join</button>
  <p id="feedback" role="alert"></p>
</form>

<script>
  const form = document.querySelector("#signup");
  const feedback = document.querySelector("#feedback");

  function checkForm(name, email, age) {
    if (name.trim() === "") {
      return "Please enter your name.";
    }
    if (!email.includes("@") || !email.includes(".")) {
      return "Please enter an email such as amina@example.com.";
    }
    if (Number.isNaN(age) || age < 16 || age > 120) {
      return "Age must be a number from 16 to 120.";
    }
    return "";
  }

  form.addEventListener("submit", function (event) {
    event.preventDefault();
    const problem = checkForm(
      form.elements.name.value,
      form.elements.email.value,
      Number(form.elements.age.value)
    );
    feedback.textContent = problem === "" ? "Thank you, you are on the list." : problem;
  });
</script>
A sign-up form for a fictional club. Save as signup.html and open in a browser.

Three things are worth noticing. event.preventDefault() stops the browser sending the form away so your code can look first. trim() removes spaces at the ends, so a name of only spaces counts as empty. And the message goes into an element marked role="alert", which tells a screen reader to announce it. The attribute novalidate switches off the browser's own bubbles so you can see your messages; remove it to compare.

Diagram

The checks the sign-up function makes, in order.

  • Is the name empty?
    • YesDo thisPlease enter your name
    • NoEmail missing @ or dot?
      • YesDo thisShow email example
      • NoAge not a number, or outside 16 to 120?
        • YesDo thisShow age range
        • NoDo thisThank you
The checks the sign-up function makes, in order.
Read this figure as text

A decision tree that checks name, then email, then age, and reports a message or accepts the form.

Start: the form is submitted. Question 1: is the name empty? If yes, show Please enter your name. If no, question 2: does the email lack an at sign or a dot? If yes, show the email message. If no, question 3: is the age not a number, or outside 16 to 120? If yes, show the age message. If no, show Thank you. The function stops at the first problem it finds.

Handling errors with try/catch

Some failures cannot be predicted by an if: text that is not valid JSON data, a missing file, a network drop. When this happens JavaScript raises an exception, and unless something handles it the script stops at that line. A try/catch block lets you try risky code and, if it fails, run a different block that reports the problem calmly.

JavaScript
function readSettings(text) {
  try {
    const settings = JSON.parse(text);
    console.log("Loaded colour:", settings.colour);
    return settings;
  } catch (error) {
    console.log("Could not read settings:", error.message);
    return { colour: "green" };   // a safe default
  } finally {
    console.log("Finished reading.");
  }
}

readSettings('{ "colour": "blue" }');
readSettings("{ colour: blue");
Reading some text as data, safely.

The first call parses fine. The second text has no quotation marks around colour and no closing bracket, so JSON.parse throws. The catch block receives an error object with a message, and the code returns a safe default so the rest of the page keeps working. The finally block, which is optional, runs in both cases. The exact wording of the message differs between browsers.

Diagram

How try, catch and finally share the work.

tryRuns first
  • Put the risky code here
  • If it works, catch is skipped
catchOnly on failure
  • Receives the error object
  • Log error.message
  • Return a safe default
finallyAlways runs
  • Runs after try or catch
  • Optional, for tidy-up
How try, catch and finally share the work.
Read this figure as text

A compare diagram showing what runs in try, catch and finally blocks.

Three columns. try: runs first; if nothing goes wrong the script continues normally and catch is skipped. catch: runs only if try throws an exception; it receives the error object and can log the message and supply a default value. finally: optional; runs every time, after try or catch, and is good for tidy-up or a final message.

The browser's developer tools

Every major browser includes developer tools. Open them with F12 or with Ctrl+Shift+I; right-clicking a page element and choosing Inspect also works. Menu names vary a little between Firefox, Chrome and Edge and change between versions, but these three panels exist in all of them.

The three panels to learn first
PanelWhat it showsUse it to
Elements (called Inspector in Firefox)The live DOM and the CSS rules applied to each elementSee why something looks wrong, test a colour change before writing it into your file
ConsoleMessages from console.log and every error, with file and line numberRead errors, print values, try one-line JavaScript
NetworkEvery file the page loaded, with its status code and sizeFind a missing stylesheet or image, a slow file or a failed request
Simulated interface: not a real screenshot

A simulated developer tools window showing the Console panel with one error.

file:///home/amina/garden/index.html
ElementsConsoleNetwork

The script ran. (index.html:12)

Uncaught ReferenceError: seedsplanted is not defined

at script.js:7

  1. Marker 1: Panel tabs: Elements, Console, Network
  2. Marker 2: Red error: says what failed
  3. Marker 3: File and line number to open
A simulated developer tools window showing the Console panel with one error.
Read this figure as text

A simulated browser window with developer tools panel tabs and a red console error with a file name and line number.

A simulated browser window showing a page called Garden club. Below it the developer tools list the tabs Elements, Console, Network. The Console is selected and shows two lines: a normal message The script ran, and a red error, Uncaught ReferenceError: seedsplanted is not defined, followed by the file and line number script.js:7. Marker 1 is the tabs, marker 2 is the red error message, and marker 3 is the file and line link.

Find an error with the Console

  1. Step 1: Open the tools

    Open any page you made, then press F12.

    You should see: A panel opens at the side or bottom with tabs such as Elements, Console and Network.

  2. Step 2: Choose Console

    Select the Console tab.

    You should see: You see any messages the page printed, and errors in red.

  3. Step 3: Cause a harmless error

    At the console prompt type seedsplanted and press Enter.

    You should see: A red ReferenceError: seedsplanted is not defined appears, because that name does not exist.

  4. Step 4: Try a calculation

    Type 2 + 3 * 4 and press Enter.

    You should see: The console prints 14, because multiplication happens before addition.

  5. Step 5: Check the Network tab

    Select Network, then refresh the page.

    You should see: A list of files appears, usually with status 200 for files that loaded. A missing file would show 404 in red.

A debugging routine

  1. Reproduce the problem and note exactly what you did.
  2. Open the Console and read the first red message, including the file and line.
  3. Open that line in your editor and look at it, and the line above it, for spelling, case, brackets and commas.
  4. Use console.log to print the values near the problem and compare them with what you expected.
  5. Change one thing at a time, refresh, and check again.

Common mistakes

  • ✖ Instead of: Forgetting event.preventDefault() and wondering why the page reloads before the message appears.

    ✔ Do this: Call event.preventDefault() at the top of the submit handler so your checks can run first.

  • ✖ Instead of: Writing an empty catch block.

    ✔ Do this: Log the error and give the user a helpful message.

  • ✖ Instead of: Treating an empty-looking name of spaces as valid.

    ✔ Do this: Use trim() before checking whether text is empty.

  • ✖ Instead of: Trusting browser validation as protection.

    ✔ Do this: Treat it as convenience and check again on the server.

If something goes wrong

The Console is empty although my page is broken.
Check you are on the Console tab, that no filter is hiding messages, and refresh the page with the tools open. Errors from before the tools were opened may not appear until you reload.
A file shows red with status 404 in the Network tab.
The browser could not find it. Check the file name, spelling, capital letters and folder in the href or src. On Linux, Style.css and style.css are different files.
My validation message never appears.
Check the element id in querySelector, that you set textContent and that the script is after the form. Use console.log inside the submit handler to confirm it runs.
F12 opens nothing.
Try Ctrl+Shift+I, or right-click the page and choose Inspect. On some laptops hold Fn and press F12.

Key terms

Exception
An error that happens while a program is running and stops it unless the code handles it.
try/catch
A JavaScript structure that tries some code and, if it fails, runs a different block instead of crashing.
Console
The developer tools panel where a page's messages and errors appear and where you can type JavaScript.
Developer tools
A set of panels built into the browser for inspecting a page, running code and seeing errors and network requests.
data validation
Data validation sets rules for what can be typed into a cell, such as a list of allowed values.
Error message
A message from the computer or program that says something went wrong and often where and why.

Practise it for real

Reading is not the same as being able to do it. Complete these on your own computer, then tick only what you have actually done. These ticks are your own honest record: nothing checks them for you.

Guided exerciseNeeds a laptop or desktop

Run and extend the sign-up form

Save the sign-up page and open it. Submit it empty, then with a bad email, then with age 12, then with correct values. Next add a rule that the name must be at least two characters long.

You have succeeded when:
Independent challengeNeeds a laptop or desktop

Challenge: find the three bugs

Make a page that deliberately contains a misspelt variable, a link to styles.css when the file is named style.css, and a JSON.parse of broken text with no try/catch. Use the Console and Network panels to find each fault, then fix them one by one.

You have succeeded when:

Knowledge check

6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.

  1. Question 1.Why validate a form in the browser?
  2. Question 2.If your page checks the email address in JavaScript, the website no longer needs to check it on the server.
  3. Question 3.Wanjiru's page reads saved settings with JSON.parse. When the saved text is damaged, the whole page stops working.What is the best fix?
  4. Question 4.Match each panel to what you use it for.
  5. Question 5.The console shows several red messages. Where should you start?
  6. Question 6.Put this debugging routine in order.
    1. Reproduce the problem
    2. Change one thing and test again
    3. Read the first console error and its line
    4. Check that line for typing slips

Summary

  • Validation checks input and shows clear messages; it helps users but does not secure a site.
  • Use HTML attributes first, then JavaScript for custom rules.
  • try/catch handles exceptions so one failure does not stop the whole script.
  • Developer tools open with F12: Elements, Console and Network are the first three panels.
  • Read the first console error, go to its line, change one thing at a time.

Checklist: can you do these?

Marking a lesson as read does not prove you can do it. Skills count as demonstrated when you pass the quiz (not yet) and complete the practical tasks (not yet).

Related lessons

References and further reading

Official sources for details that can change between versions.

On this page