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.
<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>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.
- 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
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.
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");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.
- Put the risky code here
- If it works, catch is skipped
- Receives the error object
- Log error.message
- Return a safe default
- Runs after try or catch
- Optional, for tidy-up
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.
| Panel | What it shows | Use it to |
|---|---|---|
| Elements (called Inspector in Firefox) | The live DOM and the CSS rules applied to each element | See why something looks wrong, test a colour change before writing it into your file |
| Console | Messages from console.log and every error, with file and line number | Read errors, print values, try one-line JavaScript |
| Network | Every file the page loaded, with its status code and size | Find a missing stylesheet or image, a slow file or a failed request |
The script ran. (index.html:12)
Uncaught ReferenceError: seedsplanted is not defined
at script.js:7
- Marker 1: Panel tabs: Elements, Console, Network
- Marker 2: Red error: says what failed
- Marker 3: File and line number to open
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
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.
Step 2: Choose Console
Select the Console tab.
You should see: You see any messages the page printed, and errors in red.
Step 3: Cause a harmless error
At the console prompt type
seedsplantedand press Enter.You should see: A red
ReferenceError: seedsplanted is not definedappears, because that name does not exist.Step 4: Try a calculation
Type
2 + 3 * 4and press Enter.You should see: The console prints 14, because multiplication happens before addition.
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
- Reproduce the problem and note exactly what you did.
- Open the Console and read the first red message, including the file and line.
- Open that line in your editor and look at it, and the line above it, for spelling, case, brackets and commas.
- Use
console.logto print the values near the problem and compare them with what you expected. - 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
catchblock.✔ 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
hreforsrc. On Linux,Style.cssandstyle.cssare different files. - My validation message never appears.
- Check the element id in
querySelector, that you settextContentand that the script is after the form. Useconsole.loginside 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.
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.
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.
Knowledge check
6 questions. You need 80% to pass. Mistakes here are part of learning, and you can retry as often as you like.
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.
- Client-side form validation (MDN Web Docs)
- try...catch (MDN Web Docs)
- Firefox Developer Tools (Mozilla)