如何在Joi中为正则表达式设置自定义消息 [英] How to set custom message for regex in joi
问题描述
当我验证graphql参数时,我在密码字段中收到了这样的错误消息.
When I validate my graphql arguments, I'm getting error message like this for the password field.
"password" with value "" fails to match the required pattern: /^(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*\\d)(?=\\S*[^\\w\\s])\\S{8,30}$/"
我不想在错误消息中显示正则表达式模式.因此,我尝试为密码字段设置自定义错误消息,但仍显示正则表达式模式.
I don't want to show regex pattern in the error message. So I tried to set the custom error message for the password field but still it's showing the regex pattern.
import Joi from "joi";
export default Joi.object().keys({
email: Joi.string().email().required().label("Email"),
username: Joi.string().alphanum().min(4).max(20).required().label("Username"),
name: Joi.string().min(4).max(256).required().label("Name"),
password: Joi.string()
.min(8)
.regex(/^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,30}$/)
.required()
.label("Password")
.messages({
"string.min": "Must have at least 8 characters",
"object.regex": "Must have at least 8 characters",
}),
});
我认为这不是通过 object.regex
选择正则表达式的.请帮忙.
I think it's not selecting the regex by object.regex
. Please help.
推荐答案
要知道抛出了什么错误,可以调试错误对象(通过记录错误对象),然后找到错误对象的 type
错误.
To know what error is being thrown, you can debug the error object (by logging it), and then finding the type
of error.
示例:
const Joi = require('@hapi/joi');
const joiSchema = Joi.object().keys({
password: Joi.string()
.min(8)
.regex(/^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,30}$/)
.required()
.label("Password")
.messages({
"string.min": "Must have at least 8 characters",
"object.regex": "Must have at least 8 characters",
"string.pattern.base": "enter your custom error here..."
})
});
const validationResult = joiSchema.validate({ password: "2" }, { abortEarly: false });
console.log(validationResult.error.details.map(errDetail => errDetail.type), validationResult.error);
这将输出 ["string.min","string.pattern.base"]
.由于string.min和string.pattern.base, details
有2个错误,并且 abortEarly
设置为false.
This outputs ["string.min", "string.pattern.base"]
. details
has 2 errors because of string.min and string.pattern.base, and abortEarly
is set to false.
这篇关于如何在Joi中为正则表达式设置自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!