Safe HTML Checker

A Javascript port of Simon Willison's Safe HTML Checker.

Download:

View a demo of Safe HTML Checker in action.

Features

See Simon's post about the PHP version. This is about as direct a port as I could manage.

Usage

Here's an example function which validates the given HTML, displays feedback and returns a boolean to indicate the HTML's validity:

function validateHTML(html)
{
    var v = new SafeHTMLChecker();
    v.check("<all>" + html + "</all>");
    var valid = v.isOK();

    // Provide some feedback
    if (valid)
    {
        $("feedback").innerHTML = "OK";
    }
    else
    {
        var errors = v.getErrors();
        var errorHTML = "<ul>";
        for (var i = 0, error; error = errors[i]; i++)
        {
            errorHTML += "<li>" + error + "</li>";
        }
        errorHTML += "</ul>";
        $("feedback").innerHTML = errorHTML;
    }

    return valid;
}

Dependencies

Reference

Method Kind Argument Description
SafeHTMLChecker() constructor (none) Logs the given message at a DEBUG level
check(html) instance
html
the HTML to check - the HTML should be enclosed by an <all> tag
Checks the given HTML for validity and allowed elements/attributes
isOK() instance (none) Returns true if the last HTML checked with isOK() was valid, false otherwise
getErrors() instance (none) Returns an Array of errors produced by the last call to isOK(). Each item in the array will be a String

TODO

  • The SAX parser seems to ignore empty attributes. <p onclick=""></p> will validate, but <p onclick="h"></p> will not.