Search code examples
nestjsdtoclass-validatorclass-transformer

NestJs DTO: Default value of string in dto with min length 3


I have to create a DTO that contains a field searchTerm. If this value is provided from the client then minimum length must be 3 otherwise, I should have an empty string i.e. searchTerm = '';. Is there any way I can achieve this in DTO file using class-validator and/or class-transformer package/s?

This is what I have achieved so far. It is working fine if received a value from the client but otherwise searchTerm must be equal to that value, if passed and length > 3, else should be an empty string.

@ApiPropertyOptional({default: ''})
@IsString()
@IsOptional()
@Type(() => String)
@MinLength(3)
searchTerm: string;

Solution

  • You can use conditional validation by adding @validateIf(o => o.searchTerm) before the other decorators. This checks if the searchTerm is provided, performs the other validations otherwise skips.