【发布时间】:2022-01-13 06:43:38
【问题描述】:
您好,我正在尝试使用 Joi 库向我的表单添加自定义验证。基本上我想访问一个 api 并根据数据返回错误消息或不返回错误消息。 这是我的 Joi 架构
const schema = Joi.object({
email: Joi.string()
.email({ tlds: { allow: false } })
.required(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
description: Joi.string().min(10).max(250).required().custom(isSad).message({'description.invalid':`the value provided in the description field is sad, please redact it`}),
});
在 custom() 参数中传递的 isSad 函数
const isSad = (value,helpers) => {
fetch('api url',{
method: "POST",
headers: {
"apikey": "key"
},
body:value
}).then(data => {
return data.json()
}).then(data => {
if(data.Sad > 0.49) {
return helpers.error('description.invalid');
}
}).catch(error => {
console.log('logging the error in catch', error)
})
}
据我了解,我正在向架构中的 .message() 函数发送“description.invalid”,我应该在传递的对象中使用它来显示自定义消息,但由于某种原因我不是得到显示的错误信息。如果收到的值 > 0.49,则该字段似乎被验证为有效,在我的情况下它不应该是有效的
编辑:尝试使用带有 .external() 的 schema.validateAsync 像这样
const isSad = (value,helpers) => {
console.log('logging value',value)
console.log('logging helpers',helpers)
fetch('api',{
method: "POST",
headers: {
"apikey": "apikey"
},
body:value
}).then(data => {
return data.json()
}).then(data => {
if(data.Sad > 0.49) {
throw new Error('Ur description is sad please edit it')
}
}).catch(error => {
console.log('logging the error in catch', error)
})
}
我只是像这样附加 .external(isSad) 到架构
const schema = Joi.object({
email: Joi.string()
.email({ tlds: { allow: false } })
.required(),
firstName: Joi.string().required(),
lastName: Joi.string().required(),
description: Joi.string().min(10).max(250).required().external(isSad)
});
我还必须转换使用 schema.validateAsync 的代码,因为它现在将数据作为 HTTP 响应返回。但它仍然不起作用我没有从 .external() 得到任何响应,并且描述字段已验证(就像 .external() 根本不存在一样)。
【问题讨论】:
标签: javascript reactjs validation joi