[英]Joi validation react .custom() validation in react
您好,我正在尝试使用 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 function
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)
})
}
据我了解,我在架构中向 the.message() function 发送“description.invalid”,我应该在传递的 object 中使用它来显示自定义消息,但由于某种原因我没有收到错误消息显示的消息。 如果收到的值 > 0.49,该字段似乎被验证为有效,在我的情况下它不应该是有效的
编辑:尝试使用 schema.validateAsync with.external() 像这样
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)
})
}
并且我只是 attach.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 响应返回。但它仍然不起作用我没有从 the.external() 得到任何响应,并且描述字段已经过验证(就像the.external() 根本不存在)。
发现一个问题,它说custom
仅适用于同步功能,对于 async 你需要使用external
。
在 Joi 已经验证了表单之后,我最终使用了.validate() not.validateAsync() 并进行了我自己的自定义 function 检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.