In the previous lesson you reviewed The Blue Cup by eye, with a checklist. That review is essential for judging things only a person can assess (whether a class name makes sense, whether a comment is unnecessary), but it has a clear limit: it's very easy to miss a duplicate id among hundreds of lines, a badly closed tag or a table row with one cell too many. These are precisely the errors that the browser corrects silently, without telling you. Validating the code means checking it automatically against the rules of HTML to find those faults. In this lesson you'll learn what validating means and why it's worthwhile even if the page "works", how to use the official W3C validator in three different ways, how to tell errors from warnings, how to interpret and fix the most common messages, and how to integrate validation into your editor to catch problems as you type.
Contents
- What validating is and why to do it
- The W3C validator: Nu Html Checker
- Three ways to validate: by URL, by uploading a file or by pasting the code
- Errors, warnings and information
- How to read a validator message
- The most common messages: cause and solution
- Validating CSS (in passing)
- Validating as you type: HTMLHint in VS Code
- Validating from the command line (in passing)
- Project: validating The Blue Cup
What validating is and why to do it
HTML has a specification, the HTML Living Standard maintained by the WHATWG, which you met in What Is HTML?. That specification states which elements exist, which attributes each one accepts, what can go inside what and which values are valid. Validating means running the document through a program that checks all those rules and reports every breach.
The browser forgives, but…
If you write <p>Hello <strong>world</p>, the browser doesn't show any error: it closes the strong itself and carries on. The specification defines in detail how the browser must recover from each error, and all modern browsers do it the same way. So why validate?
- What the browser corrects may not be what you intended. A
ulinside apmakes the browser close the paragraph before the list; your CSS forp ulno longer applies and an extra empty paragraph appears. - Errors can't be seen, but they have effects. A duplicate
iddoesn't break anything visible, but alabelmay end up associated with the wrong field, an anchor may jump to the wrong place andgetElementByIdwill return only the first one. - Assistive technologies and search engines work with the corrected tree, not with your intention. Incorrect nesting can produce a structure that is announced confusingly.
- Valid code is easier to maintain. Small errors pile up; when the code is clean, the next error stands out straight away.
- It's a sign of professionalism. Handing a client a site with dozens of validation errors reflects badly on the work, even if it looks fine.
What validation does not check
A valid document isn't necessarily a good document. The validator doesn't know:
- Whether the
altdescribes the image well (it only checks that it exists). - Whether you've used
articlewheresectionwas appropriate. - Whether the text of a link is understandable.
- Whether the colours have enough contrast.
- Whether the page can be used with the keyboard.
Validation is the foundation, not the goal: it checks the syntax and some structural rules. Correct semantics and accessibility also need the reviews from the previous lesson and the following ones.
A note on accessibility. Versions 2.0 and 2.1 of the WCAG accessibility guidelines included a criterion called Parsing (4.1.1) which, in practice, required well-formed HTML. Version 2.2 removed it because current browsers now recover from those errors consistently. That doesn't make validation useless: it still catches errors that do affect accessibility, such as a duplicate
idthat alabelpoints to.
The W3C validator: Nu Html Checker
The reference validator is the W3C's Nu Html Checker, available at:
It's free, it's updated as the specification changes and it's the same engine that many other tools use under the hood. Its messages are in English; in this lesson you'll see the most common ones explained.
Three ways to validate: by URL, by uploading a file or by pasting the code
When you open the validator, the Check by drop-down offers three modes:
| Mode | When to use it | Limitations |
|---|---|---|
| address (by URL) | The page is already published on the internet | It doesn't work for 127.0.0.1 or for files on your computer: the validator can't access them |
| file upload | Local files, like The Blue Cup's files right now | It validates the file as it is; it doesn't load the stylesheet or the scripts, but it doesn't need them to validate the HTML |
| text input (direct input) | Fragments, quick tests, examples from a lesson | You need to paste a complete document, or the validator will complain that the doctype or the title is missing |
For The Blue Cup, which isn't published yet, you'll use file upload:
- Open
https://validator.w3.org/nu/. - In Check by, choose file upload.
- Click Choose File (or Browse…, depending on the browser) and select
the-blue-cup/index.html. - Click Check.
The result appears below: a numbered list of messages or, if everything is fine, the message Document checking completed. No errors or warnings to show.
To try out a quick idea, text input is more convenient. Paste this and validate it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<p>Hello <strong>world</p>
</body>
</html>You'll get an error about the unclosed strong. Also try deleting the title: you'll see that it's required.
Errors, warnings and information
The validator classifies its messages into three types:
| Type | Appearance | Meaning | What to do |
|---|---|---|---|
| Error | Pink background, Error label | The document breaks a rule of the specification | Always fix it |
| Warning | Yellow background, Warning label | It isn't an error, but it usually indicates an oversight or something unnecessary | Read it and decide; it's almost always worth dealing with |
| Information (Info) | Blue or grey background, Info label | An observation, with no breach | Read it; it doesn't usually require changes |
An example of a warning: <script type="text/javascript"> produces The type attribute is unnecessary for JavaScript resources. It isn't an error, but it's noise: you can remove the type.
An example of information: <br /> produces Trailing slash on void elements has no effect and interacts badly with unquoted attribute values. It's exactly what you saw in Tags, Elements and Attributes: the slash is allowed, but it does nothing.
The professional goal is zero errors, with warnings reviewed and justified.
How to read a validator message
Every message has the same structure:
Error: Duplicate ID “privacy”.
From line 87, column 9; to line 87, column 77
<input type="checkbox" id="privacy" name="newsletter" value="yes">- Type and description: which rule is broken.
- Position: the line and column where the problematic fragment starts and ends. In VS Code,
Ctrl+Gtakes you to a specific line. - Extract: the code involved, with the problematic part highlighted.
Some tips for reading them:
- Fix from top to bottom. A single error near the start (an unclosed tag) can trigger a cascade of messages afterwards. Often, fixing the first one makes several disappear.
- Validate again after each batch of fixes. The messages change.
- Don't rely only on the line indicated. The validator reports where it detects the problem, which is sometimes a little after where it occurred. If the line looks correct, look at the previous ones.
- Read the element names in quotation marks: the message almost always tells you which element is out of place and inside which one.
The most common messages: cause and solution
| Message | What it means | Typical cause | Solution |
|---|---|---|---|
| Unclosed element “strong”. | An element has no closing tag | An oversight while typing; incomplete copying and pasting | Add </strong> in its place |
| Stray end tag “div”. | There's a closing tag that doesn't match anything open | An extra </div> after deleting a block |
Delete the extra tag or look for the missing opening tag |
| End tag “li” seen, but there were open elements. | An element is closed while others are still open inside it | Badly nested elements: <li><a>…</li></a> |
Close in the reverse order of opening: <li><a>…</a></li> |
| No “p” element in scope but a “p” end tag seen. | A </p> has no paragraph to close |
A block element (ul, div, table) inside a p: the browser closed the paragraph earlier |
Move the block out of the paragraph |
| Duplicate ID “x”. | Two elements with the same id |
Copying and pasting a field or a section | Give each one a unique id (and update any for, href="#…" and ARIA that use it) |
| An “img” element must have an “alt” attribute… | An image without alt |
An oversight | Add a descriptive alt, or alt="" if it's decorative (Adding Images) |
| Element “title” must not be empty. / Element “head” is missing a required instance of child element “title”. | The title is missing or empty |
Incomplete template | Write a unique title |
| The element “button” must not appear as a descendant of the “a” element. | One interactive control inside another | A link card with a button inside | Choose one: either it's all a link, or the button goes outside |
| A table row was 5 columns wide, which is wider than the column count established by the first row (4). | A row has more cells than the table has columns | One cell too many; a miscalculated colspan |
Recount the cells with the grid from Merging Cells |
| The “frameborder” attribute on the “iframe” element is obsolete. Use CSS instead. | An obsolete attribute | Embed code copied without checking | Remove it; the border, with CSS |
| The “align” attribute on the “td” element is obsolete. | An obsolete presentational attribute | Old code | text-align in CSS (Styling Tables) |
| The “for” attribute of the “label” element must refer to a non-hidden form control. | The label points to an id that isn't a field (or doesn't exist) |
Changing the field's id and forgetting the label |
Make for and id match |
| Bad value “” for attribute “id” on element “section”: An ID must not be the empty string. | An invalid attribute value | id="" or an id with spaces |
A valid id, without spaces, or remove the attribute |
| Bad value “12 guests” for attribute “max” on element “input”… | The value doesn't have the required format | Text where a number was expected | max="12" |
| Element “li” not allowed as child of element “div” in this context. | An element outside its required container | li without ul/ol |
Wrap it in ul or ol |
| Section lacks heading. Consider using “h2”-“h6” elements… (warning) | A section without a heading |
section used as a generic container |
Add a heading or change it to a div |
| The “navigation” role is unnecessary for element “nav”. (warning) | An ARIA role that repeats the implicit one | <nav role="navigation"> |
Remove the role (you'll see this in Using ARIA Roles and Attributes) |
Let's look at one of these cases in detail, because it's the one that confuses beginners the most:
A p can only contain inline content. When it finds the ul, the browser closes the paragraph automatically. The </p> at the end no longer has a paragraph to close and the validator says No “p” element in scope but a “p” end tag seen. In addition, the browser creates an extra empty paragraph for that orphan </p>. The solution:
You can see what the browser does with the first piece of code in DevTools > Elements: you'll see the p closed before the list and an empty <p></p> after it.
Validating CSS (in passing)
The W3C also maintains a CSS validator, known as Jigsaw:
It works in the same way (by URL, by uploading the file or by pasting the code) and catches misspelt properties (colour instead of color), invalid values or unclosed braces. Two caveats:
- It may lag a little behind new CSS features. If a recent syntax (such as some forms of media queries) appears as an error, check on MDN whether browsers support it before changing it.
- It produces lots of warnings about browser prefixes or CSS variables that aren't errors. Focus on the errors.
This course stops here with CSS; the portal's CSS course goes into its tools in depth.
Validating as you type: HTMLHint in VS Code
Uploading each file to the validator is useful before publishing, but it's more convenient to catch errors as you type. In Setting Up Your Work Environment you installed the HTMLHint extension. If you don't have it, search for it in VS Code's Extensions view.
HTMLHint underlines problems in the editor and lists them in the Problems panel (Ctrl + Shift + M). You can choose which rules it applies with a .htmlhintrc file in the root of the project:
{
"doctype-first": true,
"doctype-html5": true,
"html-lang-require": true,
"head-script-disabled": false,
"title-require": true,
"tag-pair": true,
"tagname-lowercase": true,
"attr-lowercase": true,
"attr-value-double-quotes": true,
"attr-no-duplication": true,
"id-unique": true,
"id-class-value": "dash",
"src-not-empty": true,
"alt-require": true,
"spec-char-escape": true,
"inline-style-disabled": true
}Each rule corresponds to a best practice from the previous lesson:
| Rule | What it checks |
|---|---|
doctype-first, doctype-html5 |
The HTML5 doctype is on the first line |
html-lang-require |
html has lang |
head-script-disabled: false |
Allows scripts in the head (you'll need them in Performance and Resource Loading) |
title-require |
There's a title |
tag-pair |
Every opened tag is closed |
tagname-lowercase, attr-lowercase |
Tags and attributes in lowercase |
attr-value-double-quotes |
Values in double quotes |
attr-no-duplication |
No attribute repeated on the same element |
id-unique |
No id repeated on the page |
id-class-value: "dash" |
id values and classes in lowercase with hyphens |
src-not-empty, alt-require |
Images with src and alt |
spec-char-escape |
< and > escaped in the text |
inline-style-disabled |
No style attribute |
HTMLHint doesn't replace the W3C validator: it's a linter, a tool that checks style rules and common errors, but it doesn't know every detail of the specification (for example, it doesn't catch a table row with extra cells). Ideally, use both: HTMLHint as you type, the W3C validator before publishing.
Validating from the command line (in passing)
In professional projects, validation is automated so that it runs by itself, for example before each release. Two common options, which for now you only need to know by name:
# The same W3C engine, locally (requires Java)
java -jar vnu.jar --skip-non-html the-blue-cup/
# html-validate, a validator written in JavaScript (requires Node.js)
npx html-validate "the-blue-cup/*.html"- The first line runs the Nu Html Checker on your computer (the
vnu.jarfile is downloaded from the project's official repository) and validates all the HTML files in the folder. - The second uses html-validate through
npx, which downloads and runs the tool without installing it permanently.
Both return the messages in the terminal and can be integrated into automated publishing systems. You'll come back to this, in passing, when we talk about deployment in the final project.
Project: validating The Blue Cup
- Validating the seven pages
Validate the seven pages one by one with file upload: index.html, menu.html, bookings.html, gallery.html, news.html, contact.html and privacy.html. Validate template.html too. Record the results in a table.
If you've followed the course carefully, your pages will most likely show zero errors or very few. To practise reading and fixing messages, in this project we start from a copy of the site with a few fictitious but very plausible slips, the kind made when copying and pasting. If your project doesn't have them, introduce them on purpose in a test copy, validate it, check that the validator catches them and then fix them.
| Page | Type | Message |
|---|---|---|
contact.html |
Error | Duplicate ID “privacy”. |
menu.html |
Error | A table row was 5 columns wide, which is wider than the column count established by the first row (4). |
index.html |
Error | No “p” element in scope but a “p” end tag seen. |
news.html |
Error | The “frameborder” attribute on the “iframe” element is obsolete. Use CSS instead. |
bookings.html |
Warning | The “type” attribute is unnecessary for JavaScript resources. |
gallery.html |
Information | Trailing slash on void elements has no effect… |
| The rest | — | No errors or warnings |
- Fixing the duplicate
id (contact.html)
id (contact.html)The validator's extract shows this, at the end of the contact form:
<p>
<input type="checkbox" id="privacy" name="privacy" value="accept" required>
<label for="privacy">I have read the data protection information *</label>
</p>
<p>
<input type="checkbox" id="privacy" name="newsletter" value="yes">
<label for="privacy">I would also like to receive the monthly newsletter</label>
</p>Cause: someone wanted to offer the newsletter from the contact form and copied the privacy checkbox, changing the name and the text, but not the id.
Invisible consequences: both label elements point to the first checkbox. Clicking "I would also like to receive the monthly newsletter" ticks the privacy checkbox. A screen reader announces the second checkbox without a name. And if someone does manage to tick it, a consent is sent mixed up with an enquiry.
Fix: changing the id would resolve the technical error, but the review raises a deeper question: the newsletter already has its own form in news.html, with a specific consent, as data protection law requires (Submitting Forms). The right fix is to remove the second checkbox and, if you like, add a link:
<p>
<input type="checkbox" id="privacy" name="privacy" value="accept" required>
<label for="privacy">I have read the data protection information *</label>
</p>
<p>Would you like to hear our news? <a href="news.html#newsletter">Subscribe to the monthly newsletter</a>.</p>This is an important lesson: the validator tells you where there's a problem, but the solution sometimes requires thinking beyond the message.
- Fixing the row with an extra cell (
menu.html)
menu.html)The validator flags a row in the price table, in the black coffees group:
<tr data-category="coffee" data-allergens="" data-price="1.60">
<th scope="row">Americano</th>
<td>200 ml</td>
<td>None</td>
<td>Also available with cold water</td>
<td class="price">€1.60</td>
</tr>Cause: someone wanted to add a note about the americano and wrote it in a new cell. The table has 4 columns (Product, Size, Allergens and Price, according to the first row of the thead), and this row has 5 cells.
Consequences: the browser creates a fifth phantom column with no heading; the americano's price ends up under a column that doesn't exist, out of line with the other prices; a screen reader going down the "Price" column announces "Also available with cold water" instead of "€1.60"; and the gluten-free filter script keeps working, which makes it even easier not to notice.
Fix: recount using the grid from Merging Cells. The note isn't data for a new column, but a clarification of the size or the product. It goes into the size cell:
<tr data-category="coffee" data-allergens="" data-price="1.60">
<th scope="row">Americano</th>
<td>200 ml (also available with cold water)</td>
<td>None</td>
<td class="price">€1.60</td>
</tr>What matters is that each row has as many cells as there are columns, counting colspan and the cells occupied by rows above with rowspan. In the lunch menu table, with rowspan on "Starter", "Main" and the price, the count is trickier: that's where the validator is particularly valuable.
- Fixing the paragraph with a list inside (
index.html)
index.html) <p>In our bakery, every morning we make:
<ul>
<li>Butter pastries</li>
<li>Sourdough bread</li>
</ul>
</p>Fix: the paragraph ends before the list.
<p>In our bakery, every morning we make:</p>
<ul>
<li>Butter pastries</li>
<li>Sourdough bread</li>
</ul>
- The other messages
news.html,frameborder: it was left behind when the video embed code was pasted in again. Delete it: theiframealready has no border thanks to the stylesheet. While you're at it, check that theallowis still the minimum you set in Using iframes.bookings.html,type="text/javascript": remove the attribute from the dialog'sscript. It doesn't change anything about how it works.gallery.html, trailing slash: an<img … />copied from somewhere else. Remove the slash to follow the project convention. It isn't mandatory, but it keeps the code consistent.
- Validating again
Validate the corrected pages again until they all show Document checking completed. No errors or warnings to show. Then create the .htmlhintrc file from the previous section in the root of the project, open each page in VS Code and check that the Problems panel is empty.
Add to the checklist from the previous lesson:
- [ ] W3C validator: zero errors; warnings reviewed.
- [ ] VS Code Problems panel (HTMLHint) empty.
Common Mistakes and Tips
- Validating once the page is published and not before: fix things locally with file upload; publishing with errors so you can validate by URL is putting the cart before the horse.
- Trying to validate
http://127.0.0.1:5500/by URL: the validator is on the internet and can't access your computer. Use file upload. - Fixing from the bottom up: the first error may cause the rest. Always start with the first one.
- "Fixing" the symptom rather than the cause: changing a duplicate
idwithout checking whichlabel, anchor or script used it can create a new error, this time invisible to the validator. - Thinking that "valid" means "accessible" or "well built":
alt="image"is valid. Validation is only the first filter. - Systematically ignoring warnings: they almost always point to unnecessary code or an oversight. Read them all at least once.
- Tip: validate each page when you finish it, not all of them at the end of the project. Five errors are fixed in five minutes; fifty, in an afternoon.
Exercises
Exercise 1. Without using the validator, find all the errors in this document and write down which message the validator would give for each one (roughly). Then check by pasting it into text input.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Workshops</h1>
<p>Next workshop: <strong>5 December</p>
<img src="img/workshop.jpg" width="800" height="600">
<ul>
<li><a href="bookings.html">Book your place</li></a>
</ul>
<a href="bookings.html"><button>Book</button></a>
</body>
</html>Exercise 2. Explain what happens in practice (without the validator, just in the browser) with this form and why it's serious even though it "looks fine".
<label for="email">Email address</label>
<input type="email" id="email" name="email">
<label for="email">Repeat your email address</label>
<input type="email" id="email" name="email-confirmation">Exercise 3. Count the cells in each row of this table and find the row that would give an error. Fix it.
<table>
<tr><th>Product</th><th>Size</th><th>Price</th></tr>
<tr><th scope="row">Espresso</th><td>30 ml</td><td>€1.40</td></tr>
<tr><th scope="row">Full breakfast</th><td colspan="2">Coffee + croissant</td><td>€3.50</td></tr>
<tr><th scope="row">Cortado</th><td>90 ml</td><td>€1.50</td></tr>
</table>Solutions
Solution 1.
- The
titleis missing: Element “head” is missing a required instance of child element “title”. strongleft unclosed inside thep: End tag “p” seen, but there were open elements. and Unclosed element “strong”. (the browser would carry the bold on to whatever follows).imgwithoutalt: An “img” element must have an “alt” attribute…</li></a>in the wrong order: End tag “li” seen, but there were open elements. and, afterwards, Stray end tag “a”.buttoninsidea: The element “button” must not appear as a descendant of the “a” element.
Corrected version:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Workshops | The Blue Cup</title>
</head>
<body>
<h1>Workshops</h1>
<p>Next workshop: <strong>5 December</strong></p>
<img src="img/workshop.jpg" alt="Six participants kneading bread next to the head baker" width="800" height="600">
<ul>
<li><a href="bookings.html">Book your place</a></li>
</ul>
</body>
</html>The link with the button inside was unnecessary: there's already a link to bookings. If you want it to look like a button, you give it a class and style it with CSS (like the btn class from Styling HTML Elements), but it's still an a.
Solution 2. Both label elements point to the first field, because for looks for the first element with that id. Consequences:
- Clicking "Repeat your email address" makes the cursor jump to the first field.
- The second field has no accessible name: a screen reader announces it as "edit text, email address" without saying what it is, or with the name of the first one, depending on the case.
- Any script that uses
getElementById("email")will only see the first one.
It's serious because it affects usability and accessibility without any visual symptom. The solution is a different id: id="email-confirmation" and for="email-confirmation".
Solution 3. The table has 3 columns. The full breakfast row has 1 (th) + 2 (colspan="2") + 1 = 4 columns. As the product doesn't have a size of its own, the description occupies the "Size" column, without colspan:
Take the opportunity to put between the quantities and their units on every row (30 ml, 90 ml), as in the project's menu.
Conclusion
Validating means automatically checking the code against the rules of HTML. You've seen why it's worthwhile even though the browser silently corrects errors: what it corrects may not be what you intended, and invisible errors such as a duplicate id have real effects on forms, anchors, scripts and assistive technologies. You know how to use the W3C Nu Html Checker by URL, by uploading a file or by pasting the code; how to tell errors, warnings and information apart; how to read the description, position and extract of each message and fix from top to bottom; and how to recognise the most common messages, from unclosed tags to table rows with extra cells. You also know about the CSS validator, HTMLHint for catching problems as you type and, in passing, validation from the command line. The Blue Cup passes validation without errors. But you've already seen that "valid" doesn't mean "usable by everyone": the validator doesn't know whether someone can get around the page with the keyboard, whether the colours can be told apart or whether a screen reader can skip the menu. In the next lesson, Web Accessibility Basics, you'll learn what accessibility is, who it benefits, what the WCAG guidelines ask for and how to apply them to The Blue Cup.
HTML Course
Module 1: Introduction to HTML
- What Is HTML?
- Setting Up Your Work Environment
- Basic Structure of an HTML Document
- Tags, Elements and Attributes
- Creating Your First HTML Page
- File Organisation and Paths
Module 2: Text Formatting in HTML
- Headings and Paragraphs
- Text Formatting Tags
- Lists: Ordered, Unordered and Description Lists
- Block Quotes and Preformatted Text
- Block and Inline Elements: div and span
Module 3: Links and Media in HTML
- Creating Hyperlinks
- Special Links: Anchors, Email, Phone and Downloads
- Adding Images
- Embedding Videos
- Using the Audio Element
Module 4: Tables in HTML
- Basic Table Structure
- Table Head, Body and Foot
- Merging Cells: colspan and rowspan
- Accessible Tables: caption, scope and headers
- Styling Tables
Module 5: Forms in HTML
- Creating a Basic Form
- Form Elements: input, textarea and select
- HTML5 Input Types
- Labels and Grouping: label, fieldset, legend and datalist
- Form Attributes and Validation
- Submitting Forms
Module 6: HTML5 Semantic Elements
- Introduction to Semantic HTML
- header, nav and footer
- article, section and aside
- main and figure
- Other Semantic Elements: time, address, details and dialog
Module 7: Advanced HTML Techniques
- HTML Entities
- Using iframes
- Data Attributes
- Metadata: meta, SEO and Open Graph
- Microdata and Structured Data
- Graphics in HTML: SVG and canvas
Module 8: Integrating HTML and CSS
- Linking CSS to HTML
- Inline, Internal and External CSS
- Basic CSS Selectors
- The Box Model
- Styling HTML Elements
- Introduction to Layout with Flexbox and Grid
Module 9: Responsive Web Design
Module 10: Best Practices and Accessibility
- HTML Best Practices
- Validating HTML Code
- Web Accessibility Basics
- Using ARIA Roles and Attributes
- Accessibility Testing
- Performance and Resource Loading
