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

如何为JOI自定义校验设置可生效的自定义错误信息

你代码不生效的核心原因是给helper.message()传入了错误格式的参数,helper.message()方法仅接收字符串类型的提示内容,你当前传入的对象是messages()全局/单schema配置项的传参格式,两者不能混用。

以下是三种可用的自定义错误提示实现方案:

方案1:直接返回自定义提示字符串(最简单,适合不需要多语言的场景)

field: Joi.string()
.required()
.custom((value, helper) => {
  if (!isValidField(value)) {
    // 直接传入要展示的提示文字即可
    return helper.message('该值不合法');
  }
  return value;
}),

方案2:指定错误类型,后续可统一适配多语言

field: Joi.string()
.required()
.custom((value, helper) => {
  if (!isValidField(value)) {
    // 第一个参数为错误类型,第二个参数为上下文变量(可选)
    return helper.error('any.custom');
  }
  return value;
})
// 单独为该字段配置错误提示
.messages({
  'any.custom': '该值不合法'
})

方案3:全局配置自定义错误提示

如果多个字段的自定义校验都需要复用同一套提示,可以在全局初始化JOI的时候统一配置:

// 全局配置仅需设置一次
const customJoi = Joi.defaults((schema) => schema.messages({
  'any.custom': '该值不合法'
}));

// 业务侧使用自定义的Joi实例即可
field: customJoi.string()
.required()
.custom((value, helper) => {
  if (!isValidField(value)) {
    return helper.error('any.custom');
  }
  return value;
}),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:45:02