Search code examples
jsonschema

What's the canonical way of disallowing empty strings as values?


I have a number of string properties. How do I make sure those strings are not empty? Something more declarative than minLength: 1. Similar to required in HTML, whose somewhat equivalent for text inputs is minlength=1.

{
  "type": "object",
  "patternProperties": {
    "^(?:num|str|text|check|bool)[1-3]$": {
      "type": "string",
      "maxLength": 50
    }
  },
  "additionalProperties": false
}

Solution

  • The canonical way to do this is in fact by using minLength:

    {
      "type": "object",
      "patternProperties": {
        "^(?:num|str|text|check|bool)[1-3]$": {
          "type": "string",
          "minLength": 1,
          "maxLength": 50
        }
      },
      "additionalProperties": false
    }
    

    You can always use reusable subschemas with $defs to create your own definition of an non-empty string. This also gives you a canonical and reusable name for it.

    {
      "type": "object",
      "patternProperties": {
        "^(?:num|str|text|check|bool)[1-3]$": {
          "$ref": "#/$defs/nonEmptyStringOfMaxSize"
        }
      },
      "additionalProperties": false,
      "$defs": {
        "nonEmptyStringOfMaxSize": {
          "type": "string",
          "minLength": 1,
          "maxLength": 50
        }
      }
    }