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

如何使用Joi.js校验字符串是否为指定的两个固定可选值

实现方案

这个需求完全可以通过Joi.js实现,你可以使用Joi内置的.valid()方法指定字段允许的固定值,修改后的代码如下:

// 建议同步更新TS类型定义,形成编译+运行时双重校验
type DummyValidatorInput = {
  firstInput: string;
  secondInput: 'customerTypeOne' | 'customerTypeTwo';
}

export const DummyValidator = (
  input: DummyValidatorInput,
): Joi.ValidationResult => {
  return Joi.object({
    firstInput: Joi.string().min(5).max(64).required(),
    // 补充valid方法指定允许的两个固定值
    secondInput: Joi.string().valid('customerTypeOne', 'customerTypeTwo').required()
  }).validate(input);
};

.valid()方法会对入参做严格相等校验,只有传入的值完全匹配你指定的两个字符串时才会通过校验,不符合时会返回对应校验错误。

优化建议

  • 如果后续允许的客户类型会增加,建议把固定值抽成公共常量,避免重复编码:
    const ALLOWED_CUSTOMER_TYPES = ['customerTypeOne', 'customerTypeTwo'] as const;
    type DummyValidatorInput = {
      firstInput: string;
      secondInput: typeof ALLOWED_CUSTOMER_TYPES[number];
    }
    // Joi校验规则里直接展开常量即可
    secondInput: Joi.string().valid(...ALLOWED_CUSTOMER_TYPES).required()
    
  • 可以自定义校验错误提示,降低错误排查成本:
    secondInput: Joi.string()
      .valid('customerTypeOne', 'customerTypeTwo')
      .messages({
        'any.only': 'secondInput只能是customerTypeOne或customerTypeTwo'
      })
      .required()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:54:02