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

如何在Yup验证Express控制器请求时对参数type转小写后校验

Yup 实现URL参数大小写不敏感验证

要实现type参数大小写不敏感的校验,只需要给type字段添加transform方法,在校验前将输入值转为小写即可,修改后的代码如下:

yup.object({
  params: yup.object({
    id: yup.number().min(0).max(3).required(),
    type: yup.string()
      .transform((value) => value?.toLowerCase() || value) // 转为小写,处理null/undefined情况
      .oneOf(['type1', 'type2', 'type3'])
      .required()
  })
});

关键说明:

  • 把yup.mixed()换成yup.string()更贴合参数类型,避免不必要的类型兼容问题
  • transform方法会在校验前执行,将传入的type值统一转为小写,不管用户传入Type1、TYPE1还是type1都会被处理为type1
  • 加入value?.toLowerCase() || value的判断,是为了处理value为null或undefined的情况,避免调用toLowerCase时报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:12:04