Validation on optional Parameter using class-validator in nestjs?
Solution 1
You can use the @IsOptional()
validator:
Checks if given value is empty (
=== null
,=== undefined
) and if so, ignores all the validators on the property.
Solution 2
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.
Revansiddh
Started my career with React-JS and React Native. aiming at MERN Stack. Spend free time on Stack-overflow and medium. Check out my LinkedIn Profile
Updated on July 15, 2022Comments
-
Revansiddh almost 2 years
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