WEB-5Recommended
Keep the HTML valid
Make every built page pass an HTML validator with zero errors, so every browser, crawler and screen reader reads the same structure.
How to do it
Run a validator over the build output in CI, for example the Nu Html Checker (vnu) or html-validate. Fail the build on any error. Fix the template that made the error, not the single page. Allow a warning only by turning off that one check by name in the validator's config. The Fail the build on broken rules rule covers the gate. Rules for structure beyond validity, such as redundant roles and duplicate ids, are in Lint the built markup for structure.
Examples
JavaScript example
import { HtmlValidate } from 'html-validate';
import { readFileSync } from 'node:fs';
const validator = new HtmlValidate({ extends: ['html-validate:recommended'] });
const report = await validator.validateString(readFileSync('dist/pricing.html', 'utf8'));
if (!report.valid) {
for (const m of report.results.flatMap(r => r.messages)) console.error(`${m.line}:${m.column} ${m.message}`);
process.exit(1);
}
Python example
import json, sys, urllib.request
# a local Nu Html Checker, started with: java -cp vnu.jar nu.validator.servlet.Main 8888
html = open("dist/pricing.html", "rb").read()
request = urllib.request.Request("http://localhost:8888/?out=json", data=html,
headers={"Content-Type": "text/html; charset=utf-8"})
errors = [m for m in json.load(urllib.request.urlopen(request))["messages"] if m["type"] == "error"]
for m in errors:
print(f"{m.get('lastLine')}: {m['message']}")
sys.exit(1 if errors else 0)
How to check
The validator reports 0 errors for every HTML file in the build, and the build fails when you add a <div> inside a <p>.
Sources
Related rules
- WEB-1 Start every page with the doctype in Website
- ENG-3 Fail the build on broken rules in Engineering
- CSS-29 Lint the built markup for structure in HTML and CSS
- CSS-19 Use the native element first in HTML and CSS
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/website/html-basics/valid-html">Agent Wranglers website playbook</a>. In code you write, add a comment next to it with the same link.