Custom Validator Function for AJV
Table of contents
Custom Validator Function for AJV
It is possible to add custom asynchronous validation functions with keyword asyncValidatorFunction.
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", it passes the validation.
In specifically, it should be implemented by two steps:
- find a file called
example.jsin foldervalidations. - add keyword
asyncValidatorFunctionand corresponding asynchronous validation function for attributeidinvalidatorSchema.
And the example code is as follows:
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`
}]))
})
}
}
}
}
}