Closed amarlankri closed 11 months ago
In my opinion, a validator is supposed to only return validated or not. If you would like to return different values based on where the object is validated or not, it won't be a validator anymore. Your proposed feature seems more like a transformer to me.
So I think it'd be better to use @Transform
of class-transformer.
https://github.com/typestack/class-transformer#additional-data-transformation
And in that decorator, we use function isEnum()
to determine if the object value belongs to enum or not and return corresponding result value.
The solution described in #834 has been chosen.
Description
Currently, it is possible to check that the value of a property is included in an enum definition using
isEnum
validator. Its behaviour is the following:Most of the time, this behaviour is desired but it may be too strict in other use cases. For those cases, having the ability to provide a fallback value seems to be a good solution. The behaviour would be:
Solution proposed
Creating a new validator
IsEnumWithFallback
which allows to provide a fallback function in addition to the enum type. Here is an example of its usage:This solution seems to be possible according to class validators documentation.
FAQs
fallback
rather thandefault
. As a result, as a developper, you will probably want to add logs when the fallback is called. By the way, having a function allow more complex logic if needed.isEnum
validator? I just thought it was better to distinguish clearly the two validators but I don't have real strong arguments. If you think it is better, I am open to it (however, I will have to check the feasibility of the solution).