express-openapi-validator icon indicating copy to clipboard operation
express-openapi-validator copied to clipboard

duration

Open NathanHazout opened this issue 5 years ago • 7 comments

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

NathanHazout avatar Oct 11 '20 08:10 NathanHazout

@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

cdimascio avatar Dec 28 '20 02:12 cdimascio

going to close this out. please re-open if this solution does not meet your needs

cdimascio avatar Dec 28 '20 02:12 cdimascio

I'm sorry I'm confused as to how it would validate an RFC3339 duration ...

What's this 3-letter-format?

NathanHazout avatar Jan 03 '21 17:01 NathanHazout

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

cdimascio avatar Jan 03 '21 21:01 cdimascio

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.

NathanHazout avatar Jan 04 '21 07:01 NathanHazout

@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 avatar Jan 05 '21 14:01 cdimascio

@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'});

gaston-sureify avatar Jan 05 '22 18:01 gaston-sureify