#Can you comfortably do all kinds of validation with class-validator and class-transformer?

8 messages · Page 1 of 1 (latest)

candid iris
#

I've been using "joi" lib in Express for validation. I've started working with NextJS and I'm trying to understand how to do validation properly with "class-validator" and "class-transformer". Having to write several custom validators from scratch seems a bit cumbersome.. What do you think? I might be missing something..

barren axle
#

Hey 🙂 What kind of custom validators would you be looking to write? ClassValidator has the core ones out the box which cover most use cases. I write custom validators to check for unique usernames or emails before creating a user but I haven't done much more than that - curious to what you'd be looking to use?

candid iris
# barren axle Hey 🙂 What kind of custom validators would you be looking to write? ClassValida...

Hi, Chris!

My GET request accepts query param named "keys", which is a string that contains several strings joined by comma, e.g. ?keys=key1,key2,key3. I have to split this string into array of strings based on comma separator on backend and do some operations with that array (e.g. ["key1", "key2", "key3"] later.

I would like to validate that this string input is really a string, not an empty string, not null, and able to be parsed into array of strings. After this validation, I would like to transform this string into array of strings and pass those keys in the form of array of strings, not whole string as before, to my controller and further to my service.

barren axle
#

Ah I see, well I don't think that would be too much work to get implemented to be honest! - Does this sort of validation come out the box with joi? (not familiar with it - sorry!)

candid iris
#

Sorry I was not clear in my post's text. I've been doing string validation part via joi, then parsing it to array of strings in controller or service in Express. But I see that NestJS community prefers to validate and transform input even before it reaches controller. Is it wrong observation?

barren axle
#

Ah I see, sorry! Yes this tends to be the preffered way, it means we can safely assume (with tests) that when we get to the controller, the data is validated and in the correct format to use. However, it isn't enforced so don't feel obligated to code in a way that doesn't feel right to you!

candid iris
#

I see. In case I want to transform input before controller, how should I do that? Via custom validator where I implement transform method?

barren axle
#

I'd use custom pipes to tranform the data - looks like this @Param('id', UserByIdPipe) in your controller method. https://docs.nestjs.com/pipes#custom-pipes