Skip to content

Commit 3170a1d

Browse files
authored
Merge pull request #69 from ehrmann/required-on-objects
Only apply required validator to objects
2 parents 8927433 + da104f5 commit 3170a1d

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/main/java/com/networknt/schema/RequiredValidator.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,8 @@ public RequiredValidator(String schemaPath, JsonNode schemaNode, JsonSchema pare
3535

3636
super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.REQUIRED, validationContext);
3737
if (schemaNode.isArray()) {
38-
int size = schemaNode.size();
39-
for (int i = 0; i < size; i++) {
40-
fieldNames.add(schemaNode.get(i).asText());
38+
for (JsonNode fieldNme : schemaNode) {
39+
fieldNames.add(fieldNme.asText());
4140
}
4241
}
4342

@@ -47,6 +46,10 @@ public RequiredValidator(String schemaPath, JsonNode schemaNode, JsonSchema pare
4746
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
4847
debug(logger, node, rootNode, at);
4948

49+
if (!node.isObject()) {
50+
return Collections.emptySet();
51+
}
52+
5053
Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
5154

5255
for (String fieldName : fieldNames) {

src/test/resources/tests/required.json

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,18 @@
3535
"valid": true
3636
}
3737
]
38+
},
39+
{
40+
"description": "required validation on non-object",
41+
"schema": {
42+
"required": ["foo"]
43+
},
44+
"tests": [
45+
{
46+
"description": "required not applied on null",
47+
"data": null,
48+
"valid": true
49+
}
50+
]
3851
}
3952
]

0 commit comments

Comments
 (0)