Validation on optional Parameter using class-validator in nestjs?

Revansiddh picture Revansiddh · Apr 8, 2019 · Viewed 18.1k times · Source

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

Answer

Kim Kern picture Kim Kern · Apr 8, 2019

You can use the @IsOptional() validator:

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