📅  最后修改于: 2023-12-03 15:16:40.633000             🧑  作者: Mango
Joi 是一个用于 JavaScript 中验证数据的强大库,它允许您在验证数据时指定规则,严格控制数据的有效性。然而,在使用 Joi 进行数据验证的过程中,可能会遇到一些未知的错误或问题,需要对 Joi 的错误信息进行自定义处理。
Step 1: 安装 Joi
npm install joi
Step 2: 引入 Joi
const Joi = require('joi');
Step 3: 创建 Joi 规则
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
repeat_password: Joi.ref('password'),
access_token: [
Joi.string(),
Joi.number()
],
birth_year: Joi.number().integer().min(1900).max(2013),
email: Joi.string().email({
minDomainSegments: 2,
tlds: { allow: ['com', 'net'] }
})
}).with('username', 'password').xor('password', 'access_token')
.with('password', 'repeat_password');
Step 4: 自定义 Joi 错误信息
const customErrorMessages = {
string: {
base: '`{{#label}}` is not a valid string',
email: '`{{#label}}` must be a valid email',
min: '`{{#label}}` length must be at least {{#limit}} characters long',
max: '`{{#label}}` length must be less than or equal to {{#limit}} characters long',
alphanum: '`{{#label}}` must only contain alpha-numeric characters',
},
number: {
base: '`{{#label}}` is not a valid number',
integer: '`{{#label}}` must be an integer',
},
object: {
base: '`{{#label}}` must be an object',
with: '`{{#mainWithLabel}}` must exist when `{{#label}}` exists',
xor: 'Either `{{#label}}` or `{{#otherLabel}}` must exist, not both'
},
};
const customErrorMessage = (errors) => {
if (errors && errors.length > 0) {
const { message, type } = errors[0];
if (customErrorMessages[type]) {
const template = customErrorMessages[type][message.replace(`"${errors[0].path}" `, "")];
if (template) {
return template.replace(/\{\{\#label\}\}/g, errors[0].path);
}
}
}
};
Step 5:使用自定义错误信息验证
const result = schema.validate({ username: 'abc', birth_year: 1994 });
if (result.error) {
const error = customErrorMessage(result.error.details);
console.log(error);
}
Joi 是 JavaScript 中功能强大的数据验证库,可以大大提高我们对数据的精准判断与有效性控制。但是当 Joi 出现错误时,Joi 默认的错误信息可能不太直观,为了更好的调试和定位问题,我们需要自定义 Joi 错误信息。