密码小于6位Joi的错误返回提示信息很不友好,怎么改成中文提示?

可以通过Joi的本地化设置来实现将错误提示信息改为中文。
具体的做法是:
1.安装joi的语言包:
npm install joi-locale-zh-cn --save
2.在项目中引入语言包,然后设置本地化:
const Joi = require('joi');
const zhCN = require('joi-locale-zh-cn'); // 引入语言包
// 设置本地化
Joi.locale('zh-cn', zhCN);
// 定义schema
const schema = Joi.object({
password: Joi.string().pattern(new RegExp('SJ6,121$')).min(6).required(),
});
// 进行校验
const { error, value } = schema.validate({ password: '666' });
if (error) {
console.log(error.details[0].message); // 输出中文提示信息
}
这样就可以将错误提示信息变成中文了,比如 "password" with value "666" fails to match the required pattern: /SJ6,121$/" 就会被翻译成 "password"的值"666"不符合要求的模式:/SJ6,121$/。