Ajv: Date validation fails

Created on 24 Sep 2016  路  2Comments  路  Source: ajv-validator/ajv

The validation for dates fails using "string" type and "date-time" format. From some experimentation, it seems that the failure is because the date is treated as an object and not a string. But since ajv is a JSON validator, shouldn't it validate dates as if they were strings instead of objects since that's their JSON representation?

Below is an example. By the way, I'm using version 4.3.1

Schema

{
  "type": "object",
  "properties": {
    "someDate": {
      "type": "string",
      "format": "date-time"
    }
  }
}

Object
{ someDate: new Date() }

Most helpful comment

That makes sense. Thanks for the clarification.

All 2 comments

Date indeed is an object and not a string, so your data is invalid according to your schema. If you want to validate Date objects you can do it with custom keywords, for example:

{
  "type": "object",
  "properties": {
    "someDate": {
      "instanceof": "Date"
    }
  }
}

instanceof keyword is defined in ajv-keywords.

Ajv doesn't stringify/parse data - it validates it as is. It allows for much wider range of applications, beyond data validation. If you need to you can stringify/parse objects in your code.

That makes sense. Thanks for the clarification.

Was this page helpful?
0 / 5 - 0 ratings