'Advanced conditions with class-validator (possible)?
I have TypeScript NestJS project.
I need to validate incoming DTO to my API. It can be described as "creating of project" where we have type of building (House, Flat, Garden) and depending on that type we need to define:
- House: FLOORS including ROOMS
- Flat: ROOMS
- Garden: nothing (it is one "room")
Example of house type:
{
type: HOUSE,
floors: [
{
name: "1st floor",
rooms: [
{
name: "bedroom"
}
]
}
]
}
Example of flat type:
{
type: FLAT,
rooms: [
{
name: "bedroom"
}
]
}
I've done this in past with help of AJV, but now as we migrated to NestJS, we started using class-validator.
My question is, if I can make those advanced conditionals (eg. when type is FLAT, then expect ROOMS only, but not FLOORS) in class-validator?
Solution 1:[1]
With class-validator you have the options of Conditional Validation and of Group Validation, or you could always create a custom pipe and use AJV as you are used to. For the conditional validation you could create validations based on type and then let class-validator take care of the rest
Solution 2:[2]
You have to create a custom validator for that. The docs are pretty good: https://github.com/typestack/class-validator#custom-validation-classes
When you create your custom validator class, in your implementation of validate you can access the other parameter beeing validated in the args argument. Just write your if statements and return false if they are not met. You can even return your custom error messages and implement your own decorator.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jay McDoniel |
| Solution 2 | Patrick |
