如何使用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
相关产品推荐
相关产品推荐

