networknt / json-schema-validator

A fast Java JSON schema validator that supports draft V4, V6, V7, V2019-09 and V2020-12
Apache License 2.0
822 stars 323 forks source link

Custom Validator for absent values #970

Closed gopichandch closed 6 months ago

gopichandch commented 6 months ago

Hi

We have a schema that doesn't use required field. Instead, we have a optional flag on each property to check if its a required field or not. It is designed such a way for other application use cases. Now, when I validate my Json, I want to collect Validation Messages if values are missed for optional = false properties in my json.

Can we define a custom Validator that can be triggered if a value is absent from schema. In this place, instead of running the getRequiredValidator().validate() Can we get the custom validator (maybe from Metaschema or Config) and run it.

https://github.com/networknt/json-schema-validator/blob/7cda40e52898a592c34d8445290ddccb51aa1642/src/main/java/com/networknt/schema/PropertiesValidator.java#L117

justin-tay commented 6 months ago

You can always write and register your own custom validator on your custom meta schema.

https://github.com/networknt/json-schema-validator/blob/7cda40e52898a592c34d8445290ddccb51aa1642/src/test/java/com/networknt/schema/CustomMetaSchemaTest.java#L118-L139

gopichandch commented 6 months ago

But it would work only when the value is present in the input json. If the value doesn't exist, it would just run requiredValidator. We need a custom validator here instead of the predefined RequiredValidator. Maybe like this https://github.com/gopichandch/json-schema-validator/commit/d8f00a97353571eb997e01da5ffd67246cb08f1b

justin-tay commented 6 months ago

No that wouldn't be acceptable. I don't see a reason why a custom validator doesn't work. The logic in the PropertiesValidator that is using the RequiredValidator is not using it to generate assertions. The RequiredValidator by itself will be generating the assertions separately, your implementation should be something similar to the RequiredValidator and you shouldn't be looking at the PropertiesValidator. Even if it's really required, you can just replace the PropertiesValidator with your own implementation.

justin-tay commented 6 months ago

Closing as there shouldn't be an issue creating a custom keyword / validator.