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

Custom string validator function adds unwanted key to parent object

Open rmattos500 opened this issue 4 years ago • 9 comments

Adding a custom string validator function seems to have caused my other validation to stop working correctly.

I have simplified my code down and attached a link to the repo containing an example of the issue I am running into. In the example, I am using a dummy custom string validator function that should not be causing the validation to fail, however when run, the validation fails due to some of my other rules I defined in my schema. If you comment out the custom string validator function, the rest of the rules that previously failed now pass. Thus why I believe the issue seems to stem from defining a custom string validator function.

Link to example repo: https://github.com/rmattos500/fastest-validator-issue

rmattos500 avatar Sep 08 '21 19:09 rmattos500

Confirmed, for now you can just use strict: "remove" to bypass this bug,

erfanium avatar Sep 08 '21 20:09 erfanium

repro

commenting out custom checker function will change the final result

const v = new Validator({
	// debug: true,
	useNewCustomCheckerFunction: true,
	defaults: {
		object: {
			strict: true,
		},
		string: {
			custom(value) {
				return value;
			},
		},
	},
});

const schema = {
	method: { type: "equal", value: "bar" },
	extra: "string",
};

const check = v.compile(schema);

const obj = {};
const res = check(obj);

console.log(obj);

erfanium avatar Sep 08 '21 20:09 erfanium

@icebob I think we should never call custom checker function when value is null or undefined

related to #189

erfanium avatar Sep 08 '21 20:09 erfanium

@erfanium Thanks for looking into this so quickly and for the suggested bypass!

rmattos500 avatar Sep 08 '21 21:09 rmattos500

The issue related to defaults?

icebob avatar Sep 09 '21 16:09 icebob

@icebob Nah, Run my repro code to better understand it

erfanium avatar Sep 10 '21 16:09 erfanium

Simpler repro:

const v = new Validator({
	// debug: true,
	useNewCustomCheckerFunction: true,
});

const schema = {
	extra: { type: "string", custom: value => value }
};

const check = v.compile(schema);

const obj = {};
const res = check(obj);

console.log(obj);

So the issue is that FV populates the original object with extra: undefined?

Can we move this highlighted parts into the "else" branch? image

icebob avatar Sep 13 '21 17:09 icebob

@erfanium ?

icebob avatar Sep 25 '21 11:09 icebob

Can we move this highlighted parts into the "else" branch?

I'm okay with this solution. (In fact, my solution was the same, but in another words)

erfanium avatar Sep 25 '21 14:09 erfanium