5

I need to define a JSON schema wherein the input can either be a date or empty string.

My current JSON schema is

{
    "type": "object",    
    "required": [        
        "FirstName",        
        "DateOfBirth"
    ],
    "properties": {
        "FirstName": {
            "type": "string"
        },        
        "DateOfBirth": {            
            "type": "string", 
            "format": "date"
        }
    }
}

This allows

{    
    "FirstName": "Alex",
    "DateOfBirth": "1980-10-31"
}

but not

{    
    "FirstName": "Alex",
    "DateOfBirth": ""
}

How can I define the JSON schema so that DateOfBirth allows dates as well as empty string.

A B
  • 109
  • 1
  • 8
  • Why not just make it null? – Swetank Poddar Apr 28 '20 at 15:35
  • I'm consuming the JSON message. The application that publishes the JSON message sends an empty string if DateOfBirth data is not present. I have no control over that. I was looking to see if I can get the JSON message validated using a JSON schema. – A B Apr 28 '20 at 15:47

1 Answers1

7

Use anyOf to allow for an empty string:

{
  "type": "object",
  "required": [
    "FirstName",
    "DateOfBirth"
  ],
  "properties": {
    "FirstName": {
      "type": "string"
    },
    "DateOfBirth": {
      "anyOf": [
        {
          "type": "string",
          "format": "date"
        },
        {
          "type": "string",
          "maxLength": 0
        }
      ]
    }
  }
}
Graham Parsons
  • 466
  • 7
  • 9