I need to validate some object in my NodeJS app. I have already used an awesome library express-validator, it works perfectly, but now I need to validate different object, not only requests and as far as express validator leverages validator
library, that in turn doesn't support types other than the string type.
I have found different variants like Jsonschema, Ajv
They offer great features, but I need to be able to set error message and than just catch an exception or parse it from return object. Like that
var schema = {
"id": "/SimplePerson",
"type": "object",
"properties": {
"name": {"type": "string", "error": "A name should be provided"},
"address": {"$ref": "/SimpleAddress"},
"votes": {"type": "integer", "minimum": 1}
}
};
So I can set an error message for every property.
Is there any existing solution to achieve this functionality ?
POSSIBLE SOLUTION
I have found a great library JSEN It provides necessary features.
One solution is to use Joi library : https://github.com/hapijs/joi
This library is well maintained, used and offer lots of flexibility and possible actions.
Example :
const Joi = require('joi');
const schema = Joi.object().keys({
name: Joi.string().error(new Error('A name should be provided')),
address: Joi.ref('$SimpleAddress'),
votes: Joi.number().min(1),
});
// Return result.
const result = Joi.validate(yourObject, schema);