Kevin Nagurski
Kevin Nagurski

Reputation: 1889

Prevent CodeMirror json-lint from linting empty input

I'm putting together a quick CodeMirror input for JSON and to make sure the user doesn't mess things up, I'm using the json-lint addon. My issue is that immediately on render the empty CodeMirror input is displaying a lint error. I understand that an empty input doesn't constitute valid JSON, but I'd rather it only runs when input has been made.

I'm using the addon/lint/json-lint.js add-on, which in turn is using the jsonlint package.

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

Example empty input results: enter image description here

Lint message: enter image description here

I can't see anything in the docs to disable linting for empty inputs. Am I missing something simple?

Upvotes: 1

Views: 2746

Answers (2)

Victor Albu
Victor Albu

Reputation: 73

Hope this helps:

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

So in short:

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

Which is translated to:

< yourCodeMirrorInstance >.setOption('< yourOption >',< true/false or any required value >)

Hope this helps some one.

Upvotes: 3

Andres Vargas
Andres Vargas

Reputation: 329

you could set a default value to the textarea like this

{\n\t\n}

you would have something like this

{

}

Upvotes: 0

Related Questions