Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty values validation in json schema using AJV

Tags:

json

ajv

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.

like image 869
maria zahid Avatar asked Aug 25 '17 19:08

maria zahid


People also ask

How do you validate that a JSON Schema is valid?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

What is the value of using JSON Schema for validation?

The primary strength of JSON Schema is that it generates clear, human- and machine-readable documentation. It's easy to accurately describe the structure of data in a way that developers can use for automated validation. This makes work easier for developers and testers, but the benefits go beyond productivity.

How do you use Ajv in node JS?

import Ajv from "ajv"; import { inspect } from "util"; const ajv = new Ajv({ allErrors: true }); export const validatorFactory = (schema) => { const validate = ajv. compile(schema); const verify = (data) => { const isValid = validate(data); if (isValid) { return data; } throw new Error( ajv.

What is anyOf in JSON Schema?

allOf: (AND) Must be valid against all of the subschemas. anyOf: (OR) Must be valid against any of the subschemas. oneOf: (XOR) Must be valid against exactly one of the subschemas.


1 Answers

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": "..."
      }
    }
  }
}
like image 98
Arthur Ronconi Avatar answered Nov 16 '22 04:11

Arthur Ronconi