async-validator icon indicating copy to clipboard operation
async-validator copied to clipboard

transform doesn't change value in place

Open zjlovezj opened this issue 4 years ago • 1 comments

The Readme says

Sometimes it is necessary to transform a value before validation, possibly to coerce the value or to sanitize it in some way. To do this add a transform function to the validation rule. The property is transformed prior to validation and re-assigned to the source object to mutate the value of the property in place.

I created a little example to verify.

import schema from "async-validator";
var descriptor = {
  name: {
    type: "string",
    required: true,
    pattern: /^[a-z]+$/,
    transform(value) {
      return value.trim();
    }
  }
};
var validator = new schema(descriptor);
var source = { name: " user  " };
validator.validate(source).then(() => console.log(1 + source.name + 1));

// output: 1 user  1

version: 3.2.2

zjlovezj avatar Nov 21 '19 14:11 zjlovezj

From testcase : __tests__\number.spec.js:

 it('transform does not change value', done => {
    const value = {
      v: '1',
    };
    new Schema({
      v: {
        type: 'number',
        transform: Number,
      },
    }).validate(value, errors => {
      expect(value.v).toBe('1');
      expect(errors).toBeFalsy();
      done();
    });
  });

We can find that the validator design rules don't want to change the original value. Maybe the document should be modified!

ygj6 avatar Nov 25 '19 02:11 ygj6