I want to apply validation on request payload like, there is field name with string type. But name is not compulsory field but if it exist it must execute @IsNotEmpty()
I tried something like this
@IsNotEmpty() name?: string
// it not considering ?
optional constraint
Quick look to the class-validator validation: If your object contains nested objects and you want the validator to perform their validation too, then you need to use the @ValidateNested () decorator: But for some reason It doesn't work in NestJS! Here is an easy solution. Install class-transformer package, if you haven't done it yet.
To automatically validate incoming requests, Nest provides several pipes available right out-of-the-box: The ValidationPipe makes use of the powerful class-validator package and its declarative validation decorators.
If set to true, validator will print extra warning messages to the console when something is not right. If set to true, validator will skip validation of all properties that are null in the validating object. If set to true, validator will skip validation of all properties that are null or undefined in the validating object.
We're going to use NestJS built-in function – applyDecorators, which allows merging multiple different decorators into a new one. To add your user data, just decorate your controller's method with one of the above decorators. Now, if you wanted to use your IsUserComment decorator in EditParams, you will be able to access injected user data.
You can use the @IsOptional()
validator:
Checks if given value is empty (
=== null
,=== undefined
) and if so, ignores all the validators on the property.
class-validator has an @IsOptional()
validator that you can add on along with any other validators you defined like so:
@IsOptional() @IsNotEmpty() name: string;
The decorators are commutative so validation doesn't depend on the order of the validators. If the need to validate depends on something other than presence, you can use @ValidateIf()
which takes a function argument.
Kim's answer is great. If you want to apply this behavior to all of your optional fields, you can also use skipMissingProperties: true
with your validation pipe(s).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With