I'm using class-validator in my NestJS application and have a challenge with certain fields. For instance, I have a field sample_result which can contain a number, but I'd like to be able to update or set this field to null or an empty string ('') under certain circumstances (e.g., if I want to remove the value from the database). The same applies for another field sample_comment which is a string.
Here's the relevant code:
@ApiProperty({ required: false })
@IsNumber()
@IsOptional()
sample_result?: number;
@ApiProperty({ required: false })
@IsString()
@IsOptional()
sample_comment?: string;
The challenge is that when I send a null or '' for sample_result or sample_comment, I receive a validation error. What's the correct approach or configuration with class-validator to allow null or an empty string for these specific fields while ensuring that when values are provided, they adhere to their respective validations (i.e., number for sample_result and string for sample_comment)?
Any guidance or suggestions would be greatly appreciated. Thanks!
must be a string must be a number conforming to the specified constraints
To allow null or an empty string for specific fields while still adhering to their respective validations using class-validator in your NestJS application, you can make use of conditional validation decorators.
First, import the IsNotEmpty, IsEmpty, and IsDefined decorators from the class-validator package:
import { ApiProperty } from '@nestjs/swagger';
import { IsNumber, IsString, IsOptional, ValidateIf } from 'class-validator';
export class YourDto {
@ApiProperty({ required: false })
@IsNumber()
@ValidateIf((obj) => obj.sample_result !== null && obj.sample_result !== '')
sample_result?: number | null;
@ApiProperty({ required: false })
@IsString()
@ValidateIf((obj) => obj.sample_comment !== null && obj.sample_comment !== '')
sample_comment?: string | null;
}
In the updated code, we use the ValidateIf decorator to conditionally apply the validations based on the values of sample_result and sample_comment. The validations will only be applied if the values are not null or an empty string.
By adding | null to the variable types, we allow these fields to be set as null when desired.
Now you should be able to send null or '' for sample_result and sample_comment without triggering validation errors, while still ensuring that when values are provided, they adhere to their respective validations.
I hope this helps! Let me know if you have any further questions.