json-editor icon indicating copy to clipboard operation
json-editor copied to clipboard

Question: using my own validation system

Open CTGControls opened this issue 4 years ago • 2 comments

We are using the json-editor for 90% of every thing we need in a large project but we have a few outliners. For this I have created a few editors but they are not polished enough for me to even consider doing a PR. Some of my custom editors need a completely custom validation system. Is there a way to switch out the action called on "editor.validate()". It would be nice if validate was bubbled up to the AbstractEditor not down in the core.

My problem is some of the editors we need are so far off in left field that I don't see anyone will ever need them but if I am wrong https://github.com/CTGControls/json-editor

I see I can add validators and override the styling with "showValidationErrors (errors)" but I would like to do this from the editor level. That way I would not need to pollute validator.js with mile of code.

CTGControls avatar Dec 29 '21 03:12 CTGControls

@germanbisurgi Any advice?

schmunk42 avatar Jan 10 '22 12:01 schmunk42

What do you mean with "editor level"?

If that means the root editor you can create a custom validator that it's triggered when the path is equal to root (root is the default value but notice that it can be overwritten through instance options). For example:

JSONEditor.defaults.custom_validators.push((schema, value, path) => {
  const errors = [];
  if (path === 'root') {
    if (!YOUR_CONDITION_HERE) {
      errors.push({
        path: path,
        property: 'value',
        message: 'YOUR ERROR MESSAGE HERE'
      });
    }
  }
  return errors;
});

Because the variables schema, value, path you can proof for anything to trigger the validator

You can use the path to validate at different levels. For example you can check for path === 'root.property_name.another_property_name' for a property that is nested at level 3.

You could also set a custom property into your schema and check that in your if statement. I would recommend this way because you can reuse the validator by just setting the same property in another editor schema.

germanbisurgi avatar Jan 10 '22 14:01 germanbisurgi

Feel free to reopen

germanbisurgi avatar May 08 '23 12:05 germanbisurgi