是的:如何在 ValidationError() 方法中访问 "inner" 属性

Yup: How to access the "inner" propriety in ValidationError() method

是的包含一个名为 validationError 的方法,其属性之一是“inner”。根据文档:

in the case of aggregate errors, inner is an array of ValidationErrors throw earlier in the validation chain. When the abortEarly option is false this is where you can inspect each error thrown, alternatively, errors will have all of the messages from each inner error.

但是,我不太清楚它是否正常工作。我究竟如何访问这个 属性 并在我的代码中使用它。

在这里,我尝试在这个应用程序中使用,但它似乎不起作用。

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 is thrown is by the validate* methods (validate, validateSync, validateAt, and validateSyncAt) when the validation fails. isValidSync returns a boolean and doesn't throw any errors. Use validateSync 并添加一个 catch 块以访问验证错误。

messageError.inner returns 一个空数组,因为 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"
    }
  }
]