Closed SakisTsalk closed 11 months ago
So, I think the issue here is that there's circular imports between the models and the validator, and you're honestly just getting lucky that it's working for the cats dto. These kinds of circular dependencies aren't things Nest knows about because it doesn't have any impact on the startup of the server, and would be more in class-vadliators domain to keep track of. You can try to open an issue with them about it and see if they have any suggestions.
What you can technically do is access .constructor.name
of validationArguments.object
, but it's not type safe so YMMV with that.
Generally speaking, a better option, would probably be to use a dedicated pipe that does this validation rather than forcing class-validator to work with it like this
@jmcdo29 first of all thanks for taking a look at the issue and the advice.
Yeah I am aware of using .constructor.name
I can also move the dtos to a higher tree level module as well.
I am more looking into prevending similar issues happening in the future since one can not always be too careful. In my case it took me hours to figure out why the validator was not working. So ideally an error thrown would save me all this time of debugging.
Opened an issue in class-validator
as well https://github.com/typestack/class-validator/issues/2320
Is there an existing issue for this?
Current behavior
If the same validator is being used in two different modules, and Dto Objects from both of the modules are being used inside the validator, the validator only triggers in one of the two modules.
Minimum reproduction code
https://github.com/SakisTsalk/nestjs-custom-validators-issue
Steps to reproduce
yarn install
yarn start:dev
curl --location 'http://localhost:3000/dogs/create' \ --header 'Content-Type: application/json' \ --data '{ "dog": { "name": "kittie" } }'
curl --location 'http://localhost:3000/cats/create' \ --header 'Content-Type: application/json' \ --data '{ "cat": { "name": "kittie" } }'
Expected behavior
The validate function of @CustomValidatorPipe should be triggered in both API calls.
But it is only triggered for
http://localhost:3000/cats/create
Package
Other package
class-validator, class-transformer
NestJS version
10.2.3
Packages versions
Node.js version
18.13.0
In which operating systems have you tested?
Other
No response