Skip to content

validate css properties without selector using CSSLint module Javascript

I have a textarea which is basically the CodeMirror. I want to allow the user to only type the CSS properties without selector and then validate it using CSSLint. I am not sure how I can achieve this with the help of CSSLint.

For example, I want the user to type:

font-size: 10px;

and then validate it using CSSlint without the selector. CSSLint gives error when I don’t use any selector. If a user type: h1{font-size:10px;} then it works fine but for direct property it does not. I want to know about a rule or a module that can help me in achieving the desired objective where the user can just type the CSS properties as follows:

font-size: 10px;
color: white;

and then I can easily validate whether the properties are correct or not.


You can wrap the user input in a selector, then use CSSLint.

For example, the following code reads the properties from an element with id="input" and logs them to the console.

const userInput = document.getElementById("input").value;
// Wrap the user input in a style rule so CSSLint can
// verify it.
const results = CSSLint.verify(
        "* {n" + userInput + "n}");
for (const message of results.messages) {
    // Note: Subtract 1 from the line number because
    // we added an extra line before the user input.
    console.log(message.type, message.message,
                "line", message.line - 1,
                "col", message.col);

Depending on your use case, you may want to add some extra checks to make sure there aren’t any CSSLint comments in the user input that would affect processing.

You can also add a rule to make sure that all the user input is contained in one style rule as expected:

    // rule information
    id: "unique-selector",
    name: "Check for unique selector",
    desc: "User input should consist only of "
        + "properties without selector",
    url: "",
    browsers: "All",

    // initialization
    init: function(parser, reporter) {
        "use strict";
        var rule = this,
            first = true;

        parser.addListener("startrule", function(event) {
            var selectors = event.selectors;
            if (first) {
               first = false;
            } else {
                       "Unexpected start of rule",