Empty values validation in json schema using AJV

喜夏-厌秋 提交于 2021-01-27 04:44:07

问题


I am using Ajv for validating my JSON data. I am unable to find a way to validate empty string as a value of a key. I tried using pattern, but it does not throw appropriate message.

Here is my schema

{
    "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']
}

I am using minLength to check that value should contain at least one character. But it also allows empty space.


回答1:


You can do:

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

And in the json schema:

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



回答2:


I found another way to do this using "not" keyword with "maxLength":

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

Unfortunately if someone fill the field with spaces it will be valid becouse the space counts as character. That is why I prefer the ajv.addKeyword('isNotEmpty', ...) method, it can uses a trim() function before validate.

Cheers!




回答3:


This can now be achieved using ajv-keywords.
Its a collection of custom schemas which can be used for ajv validator.

Changing schema to

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

Using ajv-keywords

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

The transform keyword specifies what transformations to be executed before validation.




回答4:


Right now there is no built in option in AJV to do so.



来源:https://stackoverflow.com/questions/45888524/empty-values-validation-in-json-schema-using-ajv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!