问题描述
当我验证我的 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*[^ws])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*[^ws])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"]
.details
由于 string.min 和 string.pattern.base 有 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 中为正则表达式设置自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!