为任何字符串类型错误显示相同的自定义错误消息 [ EXPRESS + JOI ]

Display same custom error message for any string type error [ EXPRESS + JOI ]

我有两个字段 phone 字段和 phone 代码字段。我正在使用“@hapi/joi”16.1.8 版本和 expressjs。

对于自定义错误消息,我使用了 .messages() 方法而不是 .error() 因为它非常直接。这是我尝试用 Joi 系统验证的代码:

const data = { phone, phoneCode };
const schema = Joi.object({
    phone: Joi.string().pattern(/^[0-9]{10}$/).required().messages({
        "string.base": "Sorry! It looks like something went wrong. Please try later.",
        "string.pattern.base": "Phone number must be a 10 digits number.",
        "string.empty": "Phone Number is not allowed to be empty."
    }),
    phoneCode: Joi.string().max(3).required().messages({ 
        "number": "Want to send default message if any error" 
    })
});

let validate = schema.validate(data, { abortEarly: false });

我只想在phone代码键出现错误时发送一条默认消息。我也试过

"number.*": "Want to send default message if any error"
  OR
Joi.string().max(3).required().message("Want to send default message if any error") // It give Error: Cannot apply rules to empty ruleset
  OR
phoneCode: Joi.string().max(3).message("Want to send default message if any error" ).required() // This worked upto a limit, not working if i sent phoneCode empty.

我想现在 Joi 无法直接做到这一点。如果 phoneCode 出现问题,您可以使用 .error(new Error(errMsg)) 发回单个错误:

const Joi = require('@hapi/joi');

const joiSchema = Joi.object({
    phone: Joi.string().pattern(/^[0-9]{10}$/).required().messages({
        "string.base": "Sorry! It looks like something went wrong. Please try later.",
        "string.pattern.base": "Phone number must be a 10 digits number.",
        "string.empty": "Phone Number is not allowed to be empty."
    }),
    phoneCode: Joi.string().max(3).required().error(new Error("Want to send default message if any error"))
}).error((errors) => new Error(errors.join(' ')));

const { error, value } = joiSchema.validate({ phone: 123, phoneCode: null }, { abortEarly: false });
console.log(error, value);

输出:

Error: Sorry! It looks like something went wrong. Please try later. Error: Want to send default message if any error
Object {phone: 123, phoneCode: null}

但请记住,Joi 在 .messages() 的情况下发回 ValidationError,但现在它会发回 Error。您可以根据您的要求格式化您的错误,我只是在最后加入了 space。

带有可执行代码的 RunKit:https://runkit.com/rvypandey/5e394a3b78e4df0013483771

这就是我在 JOI 中实现自定义错误消息的方法。只需从验证对象获取消息。简单好用。

const data = { phone, phoneCode };
const schema = Joi.object({
    phone: Joi.string().pattern(/^[0-9]{10}$/).required().messages({
        "string.base": "Sorry! It looks like something went wrong. Please try later",
        "string.pattern.base": "Phone number must be a 10 digits number",
        "string.empty": "Phone Number is not allowed to be empty",
        "any.required": "Phone Number is required"
    }),
    phoneCode: Joi.string().max(3).required().messages({ 
        "string.base": "Phone code must be valid",
        "string.empty": "Phone code must be valid",
        "string.max": "Phone code must be valid",
        "any.required": "Phone code must be valid"
    })
});

let validate = schema.validate(data);

if (!validate || validate.hasOwnProperty("error")) {
   console.error(`[URL: ${req.originalUrl}] [ERROR:${JSON.stringify(validate.error.details)}]`);
   return SendResponse.sendErrorMessage(res, validate.error.details[0].message);
}