首页 > 解决方案 > 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.

标签: javascriptcssnode.jsreactjs

解决方案


您可以将用户输入包装在选择器中,然后使用 CSSLint。

例如,以下代码从带有的元素中读取属性id="input"并将它们记录到控制台。

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);
}

根据您的用例,您可能需要添加一些额外的检查以确保用户输入中没有任何会影响处理的 CSSLint 注释。

您还可以添加规则以确保所有用户输入都包含在一个样式规则中,如预期:

CSSLint.addRule({
    // 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 {
               reporter.report(
                       "Unexpected start of rule",
                       selectors[0].line,
                       selectors[0].col,
                       rule);
            }
        });
    },
});

推荐阅读