javascript - 是的:如何访问 ValidationError() 方法中的“内部”属性
问题描述
是的,包含一个方法名称 validationError,其属性之一是“内部”。因此与文档:
在聚合错误的情况下,inner 是在验证链中较早抛出的 ValidationErrors 数组。当 abortEarly 选项为 false 时,您可以在此处检查引发的每个错误,或者,错误将包含来自每个内部错误的所有消息。
但是,它是否正常工作对我来说不是很清楚。我究竟是如何访问这个属性并在我的代码中使用它的。
在这里,我试图在这个应用程序中使用,但它似乎不起作用。
function validator (req, res, next) {
yup.setLocale({
mixed: {
default: 'Não é válido',
}
});
const schema = yup.object().shape({
name: yup.string().required("Legendary name is required"),
type: yup.string().required("Legendary type is required"),
description: yup.string().required("Legendary description is required").min(10)
});
let messageError = new yup.ValidationError([`${req.body.name}`, `${req.body.type}`, `${req.body.description}`]);
if(!schema.isValidSync(req.body, {abortEarly: false})) {
return res.status(400).json(messageError.inner);
}
当我失眠时运行它时,我只得到一个空数组。
有人可以帮我吗?
解决方案
ValidationError
验证失败时由validate*
方法(validate
、validateSync
、validateAt
和)抛出。返回一个布尔值并且不抛出任何错误。使用并添加一个块来访问验证错误。validateSyncAt
isValidSync
validateSync
catch
messageError.inner
返回一个空数组,因为messageError
它是一个独立的ValidationError
对象,与模式没有任何关联。
try {
schema.validateSync(req.body, { abortEarly: false })
} catch (err) {
// err is of type ValidationError
return res.status(400).json(err.inner)
}
curl -s -X POST http://localhost:5000/test | jq
[
{
"name": "ValidationError",
"path": "name",
"type": "required",
"errors": [
"Legendary name is required"
],
"inner": [],
"message": "Legendary name is required",
"params": {
"path": "name"
}
},
{
"name": "ValidationError",
"path": "type",
"type": "required",
"errors": [
"Legendary type is required"
],
"inner": [],
"message": "Legendary type is required",
"params": {
"path": "type"
}
},
{
"name": "ValidationError",
"path": "description",
"type": "required",
"errors": [
"Legendary description is required"
],
"inner": [],
"message": "Legendary description is required",
"params": {
"path": "description"
}
}
]
推荐阅读
- javascript - Vue:在助手类中导入路由器并推送路由
- json - 如何从键中获取值
- javascript - 使对象键成为等效子对象中的值
- php - 如何在 WordPress 中以编程方式更改用户的个人资料图片?
- python - 如何使用 python 编写和更新 .txt 文件?
- flutter - 如果我们在 BlocProvider 中有 3 个 BLoC,我们可以在同一个类中使用 2 个 BLoCBuilder 吗?
- php - MySQL SUM 同一行中的多列
- spring-boot - 如何在 Spring Boot 应用程序中重置会话超时
- laravel - 有没有办法让我的用户使用他们的计算机/AD 帐户立即登录网站?
- opencv - 在opencv中找到圆的质心