Checking for null values ​​in json schema using AJV

I use Ajv to validate my JSON data. I cannot find a way to check an empty string as a key value. I tried to use a template, but it does not call the corresponding message.

Here is my diagram

{
    "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 use minLength to verify that the value must contain at least one character. But it also allows empty space.

+4
source share
3 answers

There is no built-in option in AJV right now.

+1
source

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
source

, "" "maxLength":

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

, - , , . ajv.addKeyword('isNotEmpty',...), trim() .

!

0
source

Source: https://habr.com/ru/post/1684495/


All Articles