Search code examples
jsonregexjson-schema-validator

What is the correct pattern to validate the data time in json schema?


Want to have a correct pattern for below

18-11-2023 16:03:22

DD-MM-YYYY HH24:MM:SS

I am using below pattern and it works fine but if I pass date or month as single digit it doesn't work. How can I fix this?

"pattern": "^([1-9]|([012][0-9])|(3[01]))-([0]{0,1}[1-9]|1[012])-\\d\\d\\d\\d [012]{0,1}[0-9]:[0-6][0-9]:[0-6][0-9]$"


Solution

  • This blocks single digit days and months - see regex101.

    I only removed the double \\ to make it regex101 compatible.

    ^(([012][0-9])|(3[01]))-([0][1-9]|1[012])-\\d\\d\\d\\d [012]{0,1}[0-9]:[0-6][0-9]:[0-6][0-9]$
    

    In json-schema each \ has to be escaped by another \. See here