8

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

4

5 回答 5

12

你可以做:

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": "..."
      }
    }
  }
}
于 2018-02-14T02:39:12.067 回答
5

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

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

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

干杯!

于 2018-02-14T22:39:43.583 回答
2

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

于 2017-11-24T10:39:15.843 回答
2

现在可以使用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关键字指定在验证之前要执行的转换。

于 2020-07-18T16:49:58.497 回答
0

我做了与 Roconi 说的相同的事情,但想强调如何使用模式,例如“不检查逻辑”。

ajv.addKeyword({
    keyword: 'isNotEmpty',    
    validate: (schema , data) => {
        if (schema){
            return typeof data === 'string' && data.trim() !== ''
        }
        else return true;
    }
});

const schema = {
    type: "object",
    properties: {
        fname: {
            description: "first name of the user",
            type: "string",
            minLength: 3,
            isNotEmpty: false,
        },
}
于 2022-03-03T08:47:15.773 回答