Empty values validation in json schema using AJV
I found another way to do this using "not" keyword with "maxLength":
{
[...]
"type": "object",
"properties": {
"inputName": {
"type": "string",
"allOf": [
{"not": { "maxLength": 0 }, "errorMessage": "..."},
{"minLength": 6, "errorMessage": "..."},
{"maxLength": 100, "errorMessage": "..."},
{"..."}
]
},
},
"required": [...]
}
Unfortunately if someone fill the field with spaces it will be valid becouse the space counts as character. That is why I prefer the ajv.addKeyword('isNotEmpty', ...) method, it can uses a trim() function before validate.
Cheers!
Right now there is no built in option in AJV to do so.
You can do:
ajv.addKeyword('isNotEmpty', {
type: 'string',
validate: function (schema, data) {
return typeof data === 'string' && data.trim() !== ''
},
errors: false
})
And in the json schema:
{
[...]
"type": "object",
"properties": {
"inputName": {
"type": "string",
"format": "url",
"isNotEmpty": true,
"errorMessage": {
"isNotEmpty": "...",
"format": "..."
}
}
}
}