yiminghe / async-validator

validate form asynchronous

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

v4.2.5 transform won't give the transformed data when transform is not used on top-level rules

stayknight opened this issue · comments

const Schema = require('async-validator').default

const descriptor = {
  body: {
    type: 'object',
    arr: {
      type: 'array',
      defaultField: { type: 'string' },
      transform(value) {
        console.log('transform: ', value)
        if (typeof value === 'string') {
          return value.split(',')
        }
        return value
      }
    }
  }
}
const data = {
  body: {
    arr: 'a,b',
    buf: Buffer.from([1, 2, 3, 4])
  }
}

const validator = new Schema(descriptor)
validator.validate(data, { first: true }, (errors, fields) => {
  if (errors) {
    console.error(errors)
  } else {
    console.log(fields)
  }
})

The output is:
{ body: { arr: 'a,b', buf: <Buffer 01 02 03 04> } }

The field body.arr is not transformed in the callback results.
But when arr field is on the top level of descriptor, it works fine.

descriptor arr 应该包裹在 fields 中,类似下面:

const descriptor: Rules = {
  body: {
    type: 'object',
    required: true,
    fields: {
      arr: {
        type: 'array',
        defaultField: { type: 'string' },
        transform(value) {
          if (typeof value === 'string') {
            return value.split(',');
          }
          return value;
        },
        validator: (_, value) => Array.isArray(value),
        message: 'arr 不是字符串或者数组类型',
      },
    },
  },
};

我提供了一个可以运行的列子,供参考 https://stackblitz.com/edit/typescript-7dtq2r?file=transform.ts