Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation on optional Parameter using class-validator in nestjs?

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

like image 451
Revansiddh Avatar asked Apr 08 '19 10:04

Revansiddh


People also ask

How to validate nested objects with class-validator in nestjs?

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.

How do I automatically validate incoming requests in nest?

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.

What happens when validator is set to true?

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.

How to access injected user data in nestjs using decorators?

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.


3 Answers

You can use the @IsOptional() validator:

Checks if given value is empty (=== null, === undefined) and if so, ignores all the validators on the property.

like image 125
Kim Kern Avatar answered Oct 19 '22 16:10

Kim Kern


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.

like image 26
pol Avatar answered Oct 19 '22 15:10

pol


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).

like image 1
Alec Branaa Avatar answered Oct 19 '22 15:10

Alec Branaa