HTML validation with vnu

vnu is an HTML validation checker. It’s extremely easy to use and integrates well with all your other command-line tools. I installed it with brew install vnu – it’s also available through npm and pip.

I like to use it in conjunction with cURL, so I can quickly check the validation status of whatever I’m working on:

curl https://example.com | vnu -

I prefer the JSON output format, because I can pipe it into jq as follows:


// curl ENDPOINT | vnu --format json - 2>&1 | jq
{
  "messages": [
    {
      "type": "error",
      "lastLine": 3,
      "firstLine": 1,
      "lastColumn": 70,
      "firstColumn": 1,
      "message": "Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>”.",
      "extract": "  \n\n        <h2 class=\"popup-heading\" title=\"Blah Blah\"> Embed",
      "hiliteStart": 0,
      "hiliteLength": 74
    },
    {
      "type": "error",
      "lastLine": 3,
      "firstLine": 1,
      "lastColumn": 70,
      "firstColumn": 1,
      "message": "Element “head” is missing a required instance of child element “title”.",
      "extract": "  \n\n        <h2 class=\"popup-heading\" title=\"Blah Blah\"> Embed",
      "hiliteStart": 0,
      "hiliteLength": 74
    },
    {
      "type": "error",
      "lastLine": 3,
      "lastColumn": 1583,
      "firstColumn": 1559,
      "message": "Element “div” not allowed as child of element “label” in this context. (Suppressing further errors from this subtree.)",
      "extract": "n\"><label><div class=\"input-title\"> Width",
      "hiliteStart": 10,
      "hiliteLength": 25
    },

If your HTML is returned from a JSON endpoint, use another jq call to extract it from the JSON:

CURL COMMAND | jq -r .data.html | vnu --format json - 2>&1 | jq .messages

By default, vnu expects full HTML pages, and as such will complain if it’s asked to validate HTML fragments. If you’re validating HTML fragments like in the above examples, you’ll probably see messages like Start tag seen without seeing a doctype first. Expected “<!DOCTYPE html>” or Element “head” is missing a required instance of child element “title”. Don’t worry if this happens – these are only problems if you’re trying to validate a full page.

Combined with your other tools, vnu will help you fix your HTML quickly and efficiently. Enjoy!

Leave a Reply