Use custom date-time format for AJV schema validation
Your date-time values might not confirm to the ISO 8601 format, now your schema validations using the AJV NPM package are failing because of that, you might realize this very late when the correction would require a lot of changes in your code base(That’s why it is good to DRY).
I have incurred this problem.
How I have solved it was to use a custom date-time format and a regular expression to validate the date-time value, let’s have a look at the example code.
const dateTimeRegex = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9]) (2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?$');const ajv = new Ajv();ajv.addFormat('date-time', {
validate: (dateTimeString) => dateTimeRegex.test(dateTimeString);}To validate an object against a schema, I did it like:ajv.validate({
"type": "object",
"properties": {
"myDateTimeProp": {
"type": "string",
"format": "date-time",
}
},}, {myDateTimeProp: '2019-07-02 00:00:00'})//true
That is it, but just for information.
A valid ISO date-time format is like “yyyy-MM-dd’T’HH:mm:ssZZ’Z’”.
The value would be something like 2019-01-23T12:34:56.123456789Z.
With this custom date-time format, you will not need to change your data in your actual data contracts, in this case everywhere you have formatted the date-time to be something like 2019–07–02 00:00:00.
In case you are wondering how you would change a date like 2019–07–02 00:00:00 to conform to the ISO date-time format. I did it like below: