Empty values validation in json schema using AJV

maria zahid picture maria zahid · Aug 25, 2017 · Viewed 7.1k times · Source

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.

Answer

Arthur Ronconi picture Arthur Ronconi · Feb 14, 2018

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