#Can you comfortably do all kinds of validation with class-validator and class-transformer?
8 messages · Page 1 of 1 (latest)
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?
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.
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!)
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?
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!
I see. In case I want to transform input before controller, how should I do that? Via custom validator where I implement transform method?
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
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).