Custom Validator Function for AJV
Table of contents
It is possible to add custom asynchronous validation functions using the asyncValidatorFunction keyword.
A running example
If there is a model called example, the attribute id in the model would be validated. Only if its value is "1" does it pass validation.
Implementing this takes two steps:
- Find the file
example.jsin thevalidationsfolder. - Add the
asyncValidatorFunctionkeyword and the corresponding asynchronous validation function for attributeidinvalidatorSchema.
Example code:
example.prototype.validatorSchema = {
"$async": true,
"properties": {
"id": {
"asyncValidatorFunction": async function(data) {
if (data === "1") {
return true
} else {
return new Promise(function(resolve, reject) {
return reject(new Ajv.ValidationError([{
keyword: 'asyncValidatorFunction',
message: `${data} is not 1`
}]))
})
}
}
}
}
}
See also Customize Zendro for how this fits into the broader customization workflow.