[英]How to make custom error message using Joi?
如何使用 joi 制作自定义消息? 我看到很多与此相关的已回答问题,但我不知道为什么它在我这边不起作用,总是出现错误消息是“学生”不包含 1 个必填值我想要的是“学生”这个字段是必需的。
export const VALIDATION_SCHEMA = {
students: Joi.array()
.label('Student Name(s)')
.items(
Joi.object({
name: Joi.string(),
value: Joi.string()
}).required().messages('"Student" This field is required.')
),
}
您可以使用错误构造函数返回自定义错误 object,如下所示:
var schema = Joi.object().keys({
firstName: Joi.string().min(4).max(8).required().error(new
Error('error message here for first name')),
lastName: Joi.string().min(5).max(1).required().error(new
Error('error message here for last name'))
});
Joi.validate(req.body, schema, function(err, value) {
if (err) {
console.log(err.message)
return catched(err.message);
}
});
我认为最简单的方法就是这个。
const Joi = require("@hapi/joi");
export const categorySchema = Joi.object({
mobile: Joi.string().trim().regex(/^[6-9]\d{9}$/).required().messages({
"string.base": `"" should be a type of string`,
"string.empty": `"" must contain value`,
"string.pattern.base": `"" must be 10 digit number`,
"any.required": `"" is a required field`
}),
password: Joi.string().trim().required().messages({
"string.base": `"" should be a type of 'text'`,
"string.pattern.base": `"" must be 10 digit number`,
"any.required": `"" is a required field`
}),
}).required();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.