JSON Schema to check date of YYYY-MM-DD

37,354

Solution 1

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

Solution 2

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])$"
}
Share:
37,354

Related videos on Youtube

user6543599
Author by

user6543599

Updated on October 20, 2021

Comments

  • user6543599
    user6543599 over 2 years

    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"}
    
    • Saidulu Buchhala
      Saidulu Buchhala about 7 years
      Please add your sample JSON
    • user6543599
      user6543599 about 7 years
      Have updated it.
  • user6543599
    user6543599 about 7 years
    Using this regex will accept 30 February too.. thats my issue
  • Alekhya
    Alekhya about 7 years
    oh ok you just pointed out for format.. but for validity you can refer to following link. stackoverflow.com/questions/51224/…
  • GDB
    GDB over 6 years
    Just tried this. Get an error: ValueError: Invalid \escape
  • bwicklund
    bwicklund about 6 years
    double escape \\d
  • barfuin
    barfuin almost 4 years
    \d is not part of the supported subset of regex features.
  • nsx
    nsx over 3 years
    As per the JSON specification, it seems that these formats are not mandatory. Is this correct? json-schema.org/understanding-json-schema/reference/…
  • ceving
    ceving almost 3 years
    @リカルド 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."
  • Admin
    Admin over 2 years
    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.
  • Eric Aya
    Eric Aya over 2 years
    Isn't it the same solution as this answer?
  • Troy Weber
    Troy Weber almost 2 years
    Please note that the documentation also states that the "format" is more of an annotation and doesn't trigger any validation without 3rd party libraries.
  • Troy Weber
    Troy Weber almost 2 years
    The documentation states that format does not affect validation.
  • Ram Babu
    Ram Babu almost 2 years
    It has based on the json schema validator you use. I mostly use ajv which considers the format field and will validate. You may need to check with the validator you using. @TroyWeber