首页 > 解决方案 > 是的:如何访问 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);
 }

当我失眠时运行它时,我只得到一个空数组。

有人可以帮我吗?

标签: javascriptyupvalidationerror

解决方案


ValidationError验证失败时由validate*方法(validatevalidateSyncvalidateAt和)抛出。返回一个布尔值并且不抛出任何错误。使用并添加一个块来访问验证错误。validateSyncAtisValidSyncvalidateSynccatch

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"
    }
  }
]

推荐阅读