CarlosNZ / json-edit-react

React component for editing/viewing JSON/object data
https://carlosnz.github.io/json-edit-react/
MIT License
187 stars 18 forks source link

Validating data through schema #83

Closed SanderKok01 closed 5 months ago

SanderKok01 commented 5 months ago

Hi,

Firstly, thank you for implementing the drag and drop feature!

I have a question, is it possible to validate the data within the editor by using a JSONSchema or anything similar? I have need of this in my project, so I'd like to know if this is available!

CarlosNZ commented 5 months ago

I do want to implement full JSON schema validation at some point, but it's a long term plan.

But you should be able to use an external validator like jsonschema and pass an onUpdate function to json-edit-react that sends the full data object to the validator and returns an error string if it doesn't pass (and then the data won't be updated).

Something like:

onUpdate={ ( {newData} => 
  const result = validate(newData))
  // Not sure the actual syntax and return format of schema validator, but you get the idea...
  if (!result) {
   return "Does not comply with JSON schema" // this would show up in component UI as error
  }
}

It's a good use case though, I think I might update my demo site to include an example that validates against a JSON schema using this technique.

SanderKok01 commented 5 months ago

Awesome, thanks!

CarlosNZ commented 5 months ago

Hi @SanderKok01, if you check out the Demo site now, there is a "JSON Schema validation" data set to demonstrate schema validation. (I've also added a schema to the "Custom Nodes" data set).

There's a link in the blurb to the JSON schemas being enforced.

I ended up using Ajv for schema validation, was pretty straightforward.

Docs also have a section detailing how to implement: https://github.com/CarlosNZ/json-edit-react?tab=readme-ov-file#json-schema-validation