I need to validate string schema format: "date"
or format: "date-time"
to accept only ISO 8601 but also allow empty string “” (the “” requirement should be separately checked using the required schema).
JavaScript
x
7
1
{
2
"datetime1": {
3
"type": "string",
4
"format": "date-time",
5
}
6
}
7
However, the native ajv format parser does not allow empty string “” to pass. How do I make it allow empty string, and still validate ISO 8601?
Do I really have to write my own format checker using ajv.addFormat()
? I also have the same issue for "format": "email"
, where I also need “” to be valid.
Note: I can’t modify the schema, so I can’t add defaults.
Advertisement
Answer
Lets try to use oneOf
JavaScript
1
13
13
1
date_to: {
2
type: 'string',
3
oneOf: [
4
{
5
maxLength: 0
6
},
7
{
8
format: 'date-time',
9
minLength: 1
10
}
11
]
12
},
13
in the first object, it will allows empty string. In the second object, it will check input based on your format