Reputation: 544
I'm using AJV library to validate my JSON schema. I want to be able to validate Startdate
to be a string. In the case where it is not a string, it should be converted to N/A
. Currently, it only converts undefined
to N/A
.
However, in these cases it does not work as expected:
null
-> "null"If I want all of the above to be converted to an N/A
string, what would my customKeyword function look like?
JSON response:
jsonResponse: {
"Issue": {
"StartDate": "December 17, 1995 03:24:00"
}
}
schema:
var ajv = new Ajv({
useDefaults: true,
coerceTypes: 'undefined'
});
const schema = {
"type": "object",
"properties": {
"Issue": {
"type": "object",
"properties": {
"StartDate": {
"type": "string"
"default": "N/A",
"stringTypeChecker"
}
}
}
}
}
addKeyword function:
ajv.addKeyword('stringTypeChecker', {
modifying: true,
validate: function(){
let foo = []
console.log(foo)
}
});
var valid = ajv.validate(schema, jsonResponse);
Upvotes: 5
Views: 13046
Reputation: 7717
You don't need coerceTypes option.
The keyword needs to be:
ajv.addKeyword('stringTypeChecker', {
modifying: true,
schema: false, // keyword value is not used, can be true
valid: true, // always validates as true
validate: function(data, dataPath, parentData, parentDataProperty){
if (typeof data != 'string' && parentData) // or some other condition
parentData[parentDataProperty] = 'N/A';
}
});
schema:
{
"type": "object",
"properties": {
"Issue": {
"type": "object",
"properties": {
"StartDate": {
"type": "string",
"default": "N/A",
"stringTypeChecker": true
}
}
}
}
}
Upvotes: 9