Search code examples
validationormnestjs

should I add validation pipe as well as validation to ORM in nestjs?


I have an e-commerce application where I put a global validation pipe and a DTO for each request handler , Should I also put a validation on the ORM for example:(first name should be of 5 characters) ? I see that it's reasonable to put it because what if I created forgot something in a DTO , what do you think?


Solution

  • It's always a good idea to use database constraints. As you correctly mentioned you might make a mistake in your DTO or you can call the service from another service (not a controller), so you won't have payload validated.

    Another potential point of failure is that the server code might in some way, shape or form alter the payload. Imagine, you validated the input to be a string that is at least 5 characters, but then you decide to take only the first letter and capitalize it before writing to the database. I know this is a stupid example, but sometimes even more insane things might happen.

    Database constraints will provide you with guarantees. This way you will be sure that the first name is at least 5 characters.

    In other words this will ensure that "ins" and "outs" are being controlled.