【问题标题】:Empty values validation in json schema using AJV使用 AJV 的 json 模式中的空值验证
【发布时间】:2018-02-03 22:11:20
【问题描述】:

我正在使用 Ajv 来验证我的 JSON 数据。我无法找到将空字符串验证为键值的方法。我尝试使用模式,但它没有抛出适当的消息。

这是我的架构

{
    "type": "object",
    "properties": {
        "user_name": { "type": "string" , "minLength": 1},
        "user_email": { "type": "string" , "minLength": 1},
        "user_contact": { "type": "string" , "minLength": 1}
    },
    "required": [ "user_name", 'user_email', 'user_contact']
}

我正在使用 minLength 来检查该值是否应包含至少一个字符。但它也允许空白空间。

【问题讨论】:

    标签: json ajv


    【解决方案1】:

    目前 AJV 中没有内置选项可以这样做。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      ajv.addKeyword('isNotEmpty', {
        type: 'string',
        validate: function (schema, data) {
          return typeof data === 'string' && data.trim() !== ''
        },
        errors: false
      })
      

      在 json 架构中:

      {
        [...]
        "type": "object",
        "properties": {
          "inputName": {
            "type": "string",
            "format": "url",
            "isNotEmpty": true,
            "errorMessage": {
              "isNotEmpty": "...",
              "format": "..."
            }
          }
        }
      }
      

      【讨论】:

      • errors: false在这里面有什么意义。从规格中找不到
      【解决方案3】:

      我找到了另一种方法,使用带有“maxLength”的“not”关键字:

      {
        [...]
        "type": "object",
        "properties": {
          "inputName": {
            "type": "string",
            "allOf": [
              {"not": { "maxLength": 0 }, "errorMessage": "..."},
              {"minLength": 6, "errorMessage": "..."},
              {"maxLength": 100, "errorMessage": "..."},
              {"..."}
            ]
          },
        },
        "required": [...]
      }
      

      不幸的是,如果有人用空格填充该字段,它将是有效的,因为空格算作字符。这就是为什么我更喜欢 ajv.addKeyword('isNotEmpty', ...) 方法的原因,它可以在验证之前使用 trim() 函数。

      干杯!

      【讨论】:

        【解决方案4】:

        现在可以使用ajv-keywords 来实现。
        它是可用于 ajv 验证器的自定义模式的集合。

        将架构更改为

        {
          "type": "object",
          "properties": {
            "user_name": {
              "type": "string",
              "allOf": [
                {
                  "transform": [
                    "trim"
                  ]
                },
                {
                  "minLength": 1
                }
              ]
            },
           // other properties
          }
        }
        

        使用 ajv 关键字

        const ajv = require('ajv');
        const ajvKeywords = require('ajv-keywords');
        const ajvInstance = new ajv(options);
        ajvKeywords(ajvInstance, ['transform']);
        
        

        transform 关键字指定在验证之前要执行的转换。

        【讨论】:

          猜你喜欢
          • 2017-04-29
          • 2016-08-23
          • 2022-01-23
          • 2018-01-22
          • 1970-01-01
          • 2019-06-10
          • 2020-01-20
          • 2018-06-05
          • 2018-10-21
          相关资源
          最近更新 更多