NodeJS validation library for json objects

user4671628 picture user4671628 · Jun 25, 2017 · Viewed 13.3k times · Source

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.

Answer

Gatsbill picture Gatsbill · Jun 25, 2017

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);