json schema to validate datetime is after unix epoch or not

7.2k views Asked by At

I am new to json , I want to write a json schema which accepts array of time stamps in ISO8061 standard and make sure that the time is after unix epoch i.e 1 January 1970 00:00:00

the date-time in json-schema is making sure that time is ISO8061 standard but it i could not able add constraint that the time should be after unix epoch i.e 1 January 1970 00:00:00

my json shema :

{  "$schema": "http://json-schema.org/draft-04/schema#",
   "type" : "array", // array of time stamps 
   "items" : { 

        "type": "string",
        "format": "date-time"
    }  
}

json data

["1954-12-11T00:00:00Z"]

Could you please let us know is there any we can a constrain on time filed at schema level that date-time provided should be after unix epoch i.e 1 January 1970 00:00:00

2

There are 2 answers

0
canonnervio On

You can use the JSON schema date-time format, together with AJV (Another JSON schema validator) and its formatMinimum validator you can achieve what you want.

A minimum working example that you can run e.g. on this website https://npm.runkit.com/ajv would be the following:

var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true, $data: true});
require('ajv-keywords')(ajv);

var schema = {
  "properties": {
      "Date": {
          "type": "string",
          "format": "date-time",
          "formatMinimum": "1970-01-01T00:00:00.000"
      }
  }
};

var validate = ajv.compile(schema);

test({"Date": "1954-12-11T00:00:00Z"});
test({"Date": "2018-11-30T00:00:00Z"});

function test(data) {
  var valid = validate(data);
  if (valid) console.log('Valid!');
  else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}

The first test fails because the test date is in 1954, so before the hard-coded minimum date of 1970-01-01. The second test is valid since the date from today (2018-11-30) is after 1970.

2
Jason Desrosiers On

There is nothing in JSON Schema that allows comparison of dates in anyway. All it can do is constrain a string to be in the date-time format.

JSON Schema tries to constrain itself to what is supported by the JSON format. Because date-time is not a native type in JSON, it has to be represented as a string. Because it is represented as a string, JSON Schema can only apply string constraints to it.

There is one exception to this rule. integer is a type in JSON Schema, but it is not a type in JSON.