如何在Joi Schema属性中禁用多个正则表达式模式?
2026-7-15
解决Joi Schema禁用多个正则表达式模式的问题
#
你之前的两种写法都存在问题:
-
第一种用
.invalid()的思路不对,.invalid()是用来排除 具体值 的,无法用来排除匹配正则规则的字符串,所以不会生效。 -
第二种用
alternatives后加.not().match('all')的方式,因为alternatives属于类型分支规则,和你需要的string基础类型冲突,所以抛出了类型合并错误。
给你两种可行的解决方法:
方法一:用
.not()
结合
alternatives.try()
#
直接在字符串规则里用
.not()
排除匹配任意目标正则的情况,把要禁用的正则模式用
alternatives.try()
组合起来:
const schema = Joi.object({
a: Joi.string().not(
Joi.alternatives().try(
Joi.string().pattern(/^\d+$/),
Joi.string().pattern(/^Hello \d+$/)