ConditionalRequired solution with AJV — Another JsonSchema Validator JS Library

Ábner Oliveira
nerdlog
Published in
1 min readNov 11, 2016
var schema = {
"type": "ojbject",
"properties": {
"country": {
"type": "string"
},
"state": {
"type": "string"
},
"city": {
"type": "string"
}
},
"switch": [
{
"if": {
"required": [
"country"
],
"properties": {
"country": {
"type": "string",
"minLength": 1
}
}
},
"then": {
"required": [
"state"
]
},
"continue": true
},
{
"if": {
"required": [
"state"
],
"properties": {
"state": {
"type": "string",
"minLength": 1
}
}
},
"then": {
"required": [
"city"
]
},
"continue": true
},
{
"then": {
"required": [
"country"
]
}
}
]
};
// Enable JsonSchema v5 keywords on AJV
var ajv = new Ajv({v5: true});
// calls ajv validate missing all properties
ajv.validate(schema, {});
// only show errors on country because of the conditional schema
/* ajv.errors => [{"keyword":"required","dataPath":"","schemaPath":"#/switch/2/then/required","params":{"missingProperty":".country"},"message":"should have required property '.country'"}]
*/
// only show errors on state
ajv.validate(schema, { country: 'brasil'});
/* ajv.errors =>
[{"keyword":"required","dataPath":"","schemaPath":"#/switch/0/then/required","params":{"missingProperty":".state"},"message":"should have required property '.state'"}]
*/
// only show errors on city
ajv.validate(schema, { country: 'brasil', state: 'ba'});
/* ajv.errors =>[{"keyword":"required","dataPath":"","schemaPath":"#/switch/1/then/required","params":{"missingProperty":".city"},"message":"should have required property '.city'"}]
*/

--

--

Ábner Oliveira
nerdlog
Editor for

Analista de Sistemas, Especialista em Aplicações Web, Casado