19

Could someone tell me JSON Schema Validation for accepting date of YYYY-MM-DD format alone?

My sample JSON:

{"data1" : "foo", "date" :"2016-11-24"}
ivanleoncz
  • 7,457
  • 4
  • 52
  • 48
user6543599
  • 341
  • 2
  • 6
  • 18

5 Answers5

30

JSON Schema already have defined format for date, time, datetime, email, hostname, IP address. You can prefer this easier and recommended method rather than writing your own regex.

"date": {
  "type": "string",
  "format": "date"
}

Date and time format names are derived from RFC 3339, section 5.6 [RFC3339].

Reference: http://json-schema.org/latest/json-schema-validation.html#rfc.section.7.3

Ram Babu
  • 2,229
  • 3
  • 23
  • 27
  • 1
    As per the JSON specification, it seems that these formats are not mandatory. Is this correct? https://json-schema.org/understanding-json-schema/reference/string.html#format – リカルド Nov 18 '20 at 23:16
  • 1
    @リカルド I think this note is unambiguous: *"JSON Schema implementations are not required to implement this part of the specification, and many of them do not."* – ceving Jul 23 '21 at 16:36
4

add regex to json schema in schema use the following.

{
   "type": "string",
   "pattern": "^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$"
}
Alekhya
  • 264
  • 1
  • 7
0

Use below solution ... it should work good for all dates in YYYY-MM-DD or YYYY/MM/DD format. It validated leap year and restricts dates in month of Feb as well.

{
   "type": "string",
   "pattern": "(((19|20)([2468][048]|[13579][26]|0[48])|2000)[/-]02[/-]29|((19|20)[0-9]{2}[/-](0[469]|11)[/-](0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}[/-](0[13578]|1[02])[/-](0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}[/-]02[/-](0[1-9]|1[0-9]|2[0-8])))"
}
0

It is probably easier to use seconds since EPOCH or the Julian date:

{"type":"number"}

instead of a regular expression for an ISO 8601 time stamp:

{"type":"string","pattern":"^(?:[1-9][0-9]{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9][0-9](?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](?:Z|[+-][01][0-9]:[0-5][0-9])$"}

Note: Maybe the non-capturing groups have to be removed. The implementation I have used for the test, accepts it. It probably depends on the implementation.

ceving
  • 19,833
  • 10
  • 94
  • 150
0

Use built-in support for date validation:

{"type": "string", "format": "date"}
vitaly
  • 2,525
  • 4
  • 22
  • 35
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 19 '21 at 13:48
  • Isn't it the same solution as [this answer](https://stackoverflow.com/a/48664720/2227743)? – Eric Aya Oct 19 '21 at 14:13