【问题标题】:Prevent CodeMirror json-lint from linting empty input防止 CodeMirror json-lint 检测空输入
【发布时间】:2026-02-11 03:15:01
【问题描述】:

我正在为 JSON 组合一个快速的 CodeMirror 输入并确保用户不会搞砸,我正在使用 json-lint 插件。我的问题是,在呈现空 CodeMirror 输入时立即显示 lint 错误。我知道空输入不构成有效的 JSON,但我希望它仅在输入完成后运行。

我正在使用 addon/lint/json-lint.js 插件,而后者又使用 jsonlint 包。

JS

var jsonConfig = {
    mode:              'application/json',
    lineNumbers:       true,
    lint:              true,
    autoCloseBrackets: true,
    gutters:           ['CodeMirror-lint-markers']
};

$('.json textarea').each(function (pos, el) {
    CodeMirror.fromTextArea(el, jsonConfig);
});

空输入结果示例:

Lint 消息:

我在文档中看不到任何内容来禁用空输入的 linting。我错过了一些简单的东西吗?

【问题讨论】:

    标签: javascript codemirror jsonlint ui-codemirror


    【解决方案1】:

    希望这会有所帮助:

        var editor_json = CodeMirror.fromTextArea(document.getElementById("textAreaId"), {
           lineNumbers: true,
           mode: "application/json",
           gutters: ["CodeMirror-lint-markers"],
           lint: true,
           theme: '<yourThemeName>'
        });
    
        //on load check if the textarea is empty and disable validation
        editor_json.setOption("lint", editor_json.getValue().trim() );
    
        //once changes happen, if the textarea gets filled up again re-enable the validation
        editor_json.on("change", function(cm, change) {
            editor_json.setOption("lint", editor_json.getValue().trim() );
        });
    
        ///sometimes you need to refresh the CodeMirror instance to fix alignment problems or some other glitch
        setTimeout(function(){
           editor_json.refresh();
        },0);
    

    简而言之:

    editor_json.setOption("lint", editor_json.getValue().trim() );
    

    翻译为:

    .setOption('',)

    希望这对某人有所帮助。

    【讨论】:

      【解决方案2】:

      你可以像这样为 textarea 设置一个默认值

      {\n\t\n}
      

      你会有这样的东西

      {
      
      }
      

      【讨论】: