icebob / fastest-validator

:zap: The fastest JS validator library for NodeJS
MIT License
1.42k stars 89 forks source link

Incorrect validation multi array of objects #347

Open PetrChalov opened 1 month ago

PetrChalov commented 1 month ago

Hi! I encountered incorrect validation of an array of objects.

Code:

const Validator = require('fastest-validator');
const v = new Validator();

const schema = {
  $$root: true,
  type: 'array',
  items: {
    type: 'multi',
    rules: [
      {
        type: 'object',
        props: {
          data: {
            type: 'object',
            props: { position: { type: 'number' } },
          },
          meta: {
            type: 'object',
            props: { op: { type: 'equal', value: 'up' } },
          },
        },
      },
      {
        type: 'object',
        props: {
          data: {
            type: 'object',
            props: { value: { type: 'string' } },
          },
          meta: {
            type: 'object',
            props: { op: { type: 'equal', value: 'down' } },
          },
        },
      },
    ],
  },
};

const check = v.compile(schema);

const data = [
  {
    data: { position: 1 },
    meta: { op: 'down' },
  },
  {
    data: { value: 'val' },
    meta: { op: 'down' },
  },
];

console.log(check(data));
// Print
// [
//   {
//     type: 'equalValue',
//     message: "The '[0].meta.op' field value must be equal to 'up'.",
//     field: '[0].meta.op',
//     expected: 'up',
//     actual: 'down'
//   },
//   {
//     type: 'required',
//     message: "The '[0].data.value' field is required.",
//     field: '[0].data.value',
//     actual: undefined
//   }
// ]

Is there any way to make this work?

icebob commented 3 weeks ago

In your case the checked data is really wrong because the first object meta.op should be "up", but in your case is "down". When FV checks the multi rules, it can't detect which is wrong of both. Because the sight of the first rule, the meta.op value is wrong, but the sight of the second rule, the data.value is wrong. So the result is fine.