express-openapi-validator
express-openapi-validator copied to clipboard
duration
Would it be possible to validate string format duration?
See discussion: https://github.com/OAI/OpenAPI-Specification/issues/359
Definition: https://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.7.3.1
@nasht00 i believe you can solve this by using the new formats option
e.g.
formats: [
{
name: 'my-three-digit-format',
type: 'number',
// validate returns true the number has 3 digits, false otherwise
validate: (v) => /^\d{3}$/.test(v.toString()),
},
{
name: 'my-three-letter-format',
type: 'string',
// validate returns true the string has 3 letters, false otherwise
validate: (v) => /^[A-Za-z]{3}$/.test(v),
},
];
Then use it in a spec e.g.
my_property:
type: string
format: my-three-letter-format'
Create a format with a validator for duration
going to close this out. please re-open if this solution does not meet your needs
I'm sorry I'm confused as to how it would validate an RFC3339 duration ...
What's this 3-letter-format?
3-letter-format is just an example. You can use the example above as a guide to create your own custom format that validates duration. Basically, make up a name for the duration format e.g duration, then associate it with a custom validate function
Ah I see. Then yes I know I can write my own custom validators.
However, since duration is now officially supported by the specs of both json-schema and OpenAPI, my feature request was to support it built-in, just like you support date-time today.
@nasht00 i see. this makes sense. i'll reopen the ticket. ideally ajv will handle this for us, however until then (havne't checked) we could embed a customer validator to handle this by default. if you are up for creating a PR, i'll gladly review.
@cdimascio ajv supports duration validation using the ajv-formats package.
You can import the validation function by doing this:
const valDuration = ajv.compile({type: 'string', format: 'duration'});