Home > Mobile >  React monaco editor json schema validation event
React monaco editor json schema validation event

Time:04-03

I want to add custom json schema validation to my monaco editor, which looks like this:

<MonacoEditor
  language="json"
  value={jsonValue}
  editorWillMount={(monaco) => {
    monaco.languages.json.jsonDefaults.setDiagnosticsOptions(getMyJsonSchema());
  }}
/>

This setting can correctly highlight the json format errors. The question is, now I want to find a way to let my code know if the monaco editor has json format errors. Below is what I want to achieve:

const [editorHasFormatErrors, setEditorHasFormatErrors] = useState(false);

<MonacoEditor
  language="json"
  value={jsonValue}
  editorWillMount={(monaco) => {
    monaco.languages.json.jsonDefaults.setDiagnosticsOptions(getMyJsonSchema());
  }}
  formatErrorEditorListener={(editor) => {
    setEditorHasFormatErrors(editor.hasFormatErrors) // looking for a boolean indicating validation errors
  }}
/>

So basically, I'm looking for an event listener that tells me if the json format of the value entered in the monaco editor is correct or not. I searched through the docs but can't find something that achieves this. Am I missing something? Or should I use some third-party package to do this job? Thanks in advance.

Edit: By MonacoEditor I mean the Microsoft Monaco Editor here: MonacoEditor

CodePudding user response:

I'm not sure what exact library are you using, but this is how you listen for monaco editor errors (markers).

editor.onDidChangeModelDecorations(() => {
    const model = editor.getModel();
    const markers = monaco.editor.getModelMarkers(model);

    console.log({ markers })
})
  • Related