Swagger YAML定义中date-time格式未校验无效日期问题排查
Hey, I’ve run into exactly this issue before! The root problem here is that most JSON Schema validators don’t enable format validation by default—even though you’ve specified format: date-time in your schema, the validator is only checking that modified_time is a string, not that it actually matches the date-time format. On the other hand, the required field check is part of the core JSON Schema specification, so it’s enabled out of the box, which is why missing modified_time throws an error as expected.
Here are the actionable steps to fix this:
Enable format validation in your validator
Different libraries use different settings to turn on format checks. For example, if you’re using Ajv (a widely used JSON Schema validator), you need to initialize it with thestrictoption (which enables format validation by default in v8+) or explicitly enable format enforcement:const Ajv = require('ajv'); // Strict mode enables format validation for Ajv v8+ const ajv = new Ajv({ strict: true }); // Or use { format: 'full' } for more granular control over format checksCheck your validator’s documentation for the exact setting—other tools like Joi or JSON Schema Validator have similar options to turn on format validation.
Add a regex pattern as a fallback
If you want an extra safety layer (or if your validator doesn’t supportdate-timeformat checks), add apatternproperty to enforce the ISO 8601 date-time structure:modified_time: type: string format: date-time pattern: '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$' example: 2018-01-21T23:28:56.782ZThis regex will catch any string that doesn’t match the standard date-time format, even if format validation is disabled.
Confirm your validator supports date-time format
Some lightweight validators don’t implement all JSON Schema format types. If enabling format validation doesn’t work, check your library’s docs to confirm it supportsdate-timevalidation. If not, you might need to switch to a more full-featured validator or write a custom validation function for themodified_timefield.
内容的提问来源于stack exchange,提问作者efultz

