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

Should we call custom checker function, when value is `undefined` and field is `optional`?

Open erfanium opened this issue 4 years ago • 6 comments

Consider this Code:

const check = v.compile({
   foo: {
      type: "string",
      optional: true,
      custom(v) {
         console.log("custom");
         return v;
      },
   },
});

check({});

Currently, the custom function is called. Should custom function to be called? I don't think so

erfanium avatar Sep 12 '20 21:09 erfanium

Hmm, good question. The logic will be if we shouldn't call it but I don't know somebody uses it with the current logic.

icebob avatar Sep 13 '20 08:09 icebob

@icebob The problem with current logic is that you should always write if (!value) return value piece of code in custom function, Most of the time I forget this.

but I don't know somebody uses it with the current logic..

We can release v2.0.0, I think we should do the right thing and not get involved in backward compatibility.

erfanium avatar Sep 13 '20 10:09 erfanium

My problem with major versions, that I can't update it in the Moleculer just in the next major version. A more friendly way can be a Validator option (e.g. dontCallOptionalCustomWithoutValue maybe should a better and shorter name) which turn on/off the current/new logic. And if the default value is the current logic it doesn't cause breaking change.

icebob avatar Sep 14 '20 16:09 icebob

@icebob I did not work with Moleculer much, but it is better to give the user the option to choose which version of FV to use. According to the principle of separation of concerns, this concern is about the Moleculer, not FV

erfanium avatar Sep 14 '20 18:09 erfanium

another related issue is that custom checker function & missing property cause the property to appear on validated object:

const schema = {
  field: {type: 'string', optional: true, custom(value, errors) {
      // your validation logic
      return value;
    }
}

const obj = {};
validator.compile(schema)(obj);

// now obj === {field: undefined}

hugebdu avatar Mar 15 '21 13:03 hugebdu

This should be fixed in next major update

erfanium avatar Mar 16 '21 08:03 erfanium