Skip to content

Commit 93fa3bb

Browse files
authored
Add document for custom validators
1 parent 49215e6 commit 93fa3bb

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

doc/validators.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,70 @@ If `if` is valid, `then` must also be valid (and `else` is ignored.) If `if` is
1313

1414
For usage, please refer to the test cases at https://github.com/networknt/json-schema-validator/blob/master/src/test/resources/draft7/if-then-else.json
1515

16+
### Custom Validators
17+
````
18+
@Bean
19+
public JsonSchemaFactory mySchemaFactory() {
20+
// base on JsonMetaSchema.V201909 copy code below
21+
String URI = "https://json-schema.org/draft/2019-09/schema";
22+
String ID = "$id";
23+
List<Format> BUILTIN_FORMATS = new ArrayList<Format>(JsonMetaSchema.COMMON_BUILTIN_FORMATS);
24+
25+
JsonMetaSchema myJsonMetaSchema = new JsonMetaSchema.Builder(URI)
26+
.idKeyword(ID)
27+
.addFormats(BUILTIN_FORMATS)
28+
.addKeywords(ValidatorTypeCode.getNonFormatKeywords(SpecVersion.VersionFlag.V201909))
29+
// keywords that may validly exist, but have no validation aspect to them
30+
.addKeywords(Arrays.asList(
31+
new NonValidationKeyword("$schema"),
32+
new NonValidationKeyword("$id"),
33+
new NonValidationKeyword("title"),
34+
new NonValidationKeyword("description"),
35+
new NonValidationKeyword("default"),
36+
new NonValidationKeyword("definitions"),
37+
new NonValidationKeyword("$defs") // newly added in 2018-09 release.
38+
))
39+
// add your custom keyword
40+
.addKeyword(new GroovyKeyword())
41+
.build();
42+
43+
return new JsonSchemaFactory.Builder().defaultMetaSchemaURI(myJsonMetaSchema.getUri())
44+
.addMetaSchema(myJsonMetaSchema)
45+
.build();
46+
}
47+
48+
public class GroovyKeyword extends AbstractKeyword {
49+
private static final Logger logger = LoggerFactory.getLogger(GroovyKeyword.class);
50+
51+
public GroovyKeyword() {
52+
super("groovy");
53+
}
54+
55+
@Override
56+
public AbstractJsonValidator newValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) throws JsonSchemaException, Exception {
57+
// you can read validator config here
58+
String config = schemaNode.asText();
59+
return new AbstractJsonValidator(this.getValue()) {
60+
@Override
61+
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
62+
// you can do validate here
63+
logger.info("config:{} path:{} node:{}", config, at, node);
64+
65+
return Collections.emptySet();
66+
}
67+
};
68+
}
69+
}
70+
````
71+
You can use GroovyKeyword like below:
72+
````
73+
{
74+
"type": "object",
75+
"properties": {
76+
"someProperty": {
77+
"type": "string",
78+
"groovy": "SomeScript.groovy"
79+
}
80+
}
81+
}
82+
````

0 commit comments

Comments
 (0)