I am using class-validator in a NestJS project and facing an issue regarding validation. I want to allow properties to accept values like null, '' (empty string), or undefined without validation. But if there's any other value, it should go through the validation decorators.
Here's an example of the properties:
@ApiProperty({ required: false })
@IsNumber()
@IsOptional()
sample_result?: number;
@ApiProperty({ required: false })
@IsString()
@IsOptional()
sample_comment?: string;
Even with @IsOptional() and @ValidateIf() decorators, I'm not achieving the desired behavior. If I send a null value for sample_result, it still throws an error like:
"isNumber": "sample_result must be a number conforming to the specified constraints"
Has anyone faced a similar issue or knows how to bypass validation for null, '', and undefined values while enforcing it for other values?
I tried using the @IsOptional() decorator from class-validator in my NestJS application to allow properties to accept values like null, '' (empty string), or undefined without any validation. My expectation was that if I provided any of these values, the validation would bypass without any errors.
However, if there was any other value provided (like a string for a number field), I expected it to undergo the validation and throw an error if it didn't match the validation rules.
Despite using the @IsOptional() decorator, whenever I send a null value for a property that is decorated with @IsNumber(), I am receiving an error:
"isNumber": "sample_result must be a number conforming to the specified constraints"
This is not what I expected, as I assumed @IsOptional() would allow null values without any issues.
Received data: ${JSON.stringify(errors)}); return new BadRequestException(errors); }, }), );