class-validator: ValidateNested not working
Hello,
i have something like this:
class Day
{
@IsMilitaryTime()
from: string;
@IsMilitaryTime()
to: string;
}
export class DailyCalendar
{
@IsDefined() // do i need it?
@ValidateNested()
monday: Day;
...
}
When calling the route with this body: { "monday": { "from": "foo" } } or { "monday": { } } it doesn’t throw an error.
Also when not using @IsDefined() i can call the route without monday property and it doesn’t throw an error.
The class will be created, but not validated.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 21 (9 by maintainers)
Well, I’ve just solved my problem, I share the solution:
DummyDto (main class)
SubDto file:
This dto works:
This dto fails:
Note for NestJs users:
The ValidatorPipe is very similar to the existing on docs.
I hope this helps somebody.
I have the same problem. This work for me:
@Typeis from module class-transformer.I just ran into this unexpected bug. It works fine if I have an actual instance of the type, but non-instances are ignored. E.g., in one of my unit tests, I’m casting a string to
any, when it should be a class instance, and assigning theanyto an array property on the parent. Theanyvalue passes as valid. I would expect this to throw an error because a string is not an instance of my expected type.Example:
The reason I even tried this is because we want to have more control over error responses, so we turned off validation in routing-controllers and call the validation method manually. This allows for clients to pass in any info they want and it by-passes the validation routine.
https://github.com/typestack/class-validator#validating-plain-objects
Hi @Masterrg I’m also using Nestjs, could you share a simple example of how you do nested validation? I try with plainToClass on ValidatorPipe but only validates parent class.
I have another issue (using TypeScript 2.5.3, NodeJS 6.10.3 and class-validator 0.7.3):
Last line throws an error
Only objects and arrays are supported to nested validation(https://github.com/pleerock/class-validator/blob/master/src/validation/ValidationExecutor.ts#L208).If I remove the line
obj.nested = null as any, thenobj.nestedisundefinedand everything works as expected - in this case I receive a validation error thatobj.nestedmust be defined.If I remove
IsDefinedthen the error is still thrown.Hey @pleerock
any updates on this issue? We are using NestJS and are implementing a validation pipe (combination of class-transformer and class-validator). Unfortunately @ ValidateNested() still doesn’t work as it doesn’t return any errors in obviously wrong objects.
Best Regards