json - 使用 AJV 在 json 模式中验证空值

标签 json ajv

我正在使用 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 来检查该值应至少包含一个字符。但它也允许留出空间。

最佳答案

你可以这样做:

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": "..."
      }
    }
  }
}

关于json - 使用 AJV 在 json 模式中验证空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45888524/

相关文章:

java - 使用 Jackson 序列化对象列表 : "deep" and/or "shallow"

node.js - 如何使用 AJV 为 JSON 类型定义 (JTD) 指定最大或最小数量?

javascript - 如何在 AJV 错误的错误消息中使用属性名称

node.js - Json 架构 : Validating Arrays

typescript - 类验证器的高级条件(可能)?

c# - 在 JSON web-api 上公开的对象 - 如何阻止属性名称更改大小写?

javascript - 如何格式化字符串以修复 Javascript 中的缩进?

ruby-on-rails - Ruby on Rails - 连接两个表将结果添加到 JSON

json - Apache Airflow : airflow initdb results in "ImportError: No module named json"

javascript - 如何从 AJV 错误中获取 "title"?