Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 921
Baterka Avatar asked Nov 16 '22 16:11

Baterka


1 Answers

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

like image 197
Jay McDoniel Avatar answered Jan 06 '23 11:01

Jay McDoniel