You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Joi编写同时兼容JS Date、Firestore Date和null的校验规则?

Joi 兼容多日期类型的校验规则实现

你可以通过Joi内置的alternatives()多类型匹配语法实现需求,完整的校验规则如下:

const workSchema = Joi.object({
  timeline_created: Joi.alternatives()
    // 兼容原生JS Date类型和null值
    .try(Joi.date().allow(null))
    // 兼容Firestore Timestamp结构
    .try(Joi.object({
      _seconds: Joi.number().required(),
      _nanoseconds: Joi.number().required()
    }).unknown(true)) // 可选配置:如果Timestamp对象存在Firestore内置的其他属性、方法,开启后可避免额外属性触发校验失败
    .required()
})

规则说明

  • Joi.alternatives().try():只要传入值符合任意一个try块内的校验规则,即可通过校验
  • 规则保留了required约束:timeline_created字段必须存在,值可以是null、原生Date对象、符合结构的Firestore Timestamp对象三种类型
  • 如果你确定业务场景中的Timestamp对象只会有_seconds和_nanoseconds两个属性,可以去掉.unknown(true)配置,进一步收紧校验规则

校验测试示例

你可以通过以下用例验证规则有效性:

// 用例1:null值,校验通过
workSchema.validate({ timeline_created: null })
// 用例2:原生Date对象,校验通过
workSchema.validate({ timeline_created: new Date() })
// 用例3:Firestore Timestamp结构对象,校验通过
workSchema.validate({ timeline_created: { _seconds: 1637258607, _nanoseconds: 349000000 } })

内容的提问来源于stack exchange,提问作者charnould

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:45:02