用于 json 对象的 NodeJS 验证库

9 validation json jsonschema node.js ajv

我需要验证我的 NodeJS 应用程序中的某个对象。我已经使用了一个很棒的库express-validator,它工作得很好,但是现在我需要验证不同的对象,不仅是请求,而且就 express 验证器利用validator库而言,它又不支持字符串类型以外的类型。

我发现了不同的变体,如JsonschemaAjv

它们提供了很棒的功能,但我需要能够设置错误消息,而不仅仅是捕获异常或从返回对象中解析它。像那样

 var schema = {
    "id": "/SimplePerson",
    "type": "object",
    "properties": {
      "name": {"type": "string", "error": "A name should be provided"},
      "address": {"$ref": "/SimpleAddress"},
      "votes": {"type": "integer", "minimum": 1}
    }
  };
Run Code Online (Sandbox Code Playgroud)

所以我可以为每个属性设置错误消息。

是否有任何现有的解决方案来实现此功能?

可能的解决方案

我找到了一个很棒的库JSEN它提供了必要的功能。

may*_*yor 7

可用于 JSON 验证的三个强大且流行的库是

AJV:https: //github.com/epoberezkin/ajv

JOI: https: //github.com/hapijs/joi

JSON 验证器: https: //github.com/tdegrunt/jsonschema

所有这些库都允许您验证不同的数据类型、进行条件验证以及设置自定义错误消息。


Gat*_*ill 5

一种解决方案是使用 Joi 库:https : //github.com/hapijs/joi

这个库维护和使用得很好,并提供了很多灵活性和可能的​​操作。

例子 :

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);
Run Code Online (Sandbox Code Playgroud)