gpt4 book ai didi

error-handling - 如何在Joi中为正则表达式设置自定义消息

转载 作者:行者123 更新时间:2023-12-03 08:18:00 25 4
gpt4 key购买 nike

当我验证graphql参数时,我在密码字段中收到了这样的错误消息。

"password" with value "" fails to match the required pattern: /^(?=\\S*[a-z])(?=\\S*[A-Z])(?=\\S*\\d)(?=\\S*[^\\w\\s])\\S{8,30}$/"
我不想在错误消息中显示正则表达式模式。因此,我尝试为密码字段设置自定义错误消息,但仍显示正则表达式模式。
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选择正则表达式。请帮忙。

最佳答案

要知道抛出什么错误,可以调试错误对象(通过记录错误对象),然后找到错误的type
例:

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"]details由于string.min和string.pattern.base而有2个错误,并且 abortEarly设置为false。

关于error-handling - 如何在Joi中为正则表达式设置自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63584205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com