Search code examples
validationnestjsclass-validatorclass-transformer

How to make more advanced conditional validation using class-validator?


My validation requirements for one varriable depends on the value of the other varriable. I don't know how to create my DTO properly.

Look for my example:

export class CreateItemDto {
    @IsBoolean()
     price_show: boolean;
   
     @ValidateIf(o => o.price_show === true)
     @IsNumber()
     @Min(10)
     //TODO: if price_show is false, then price MUST BE NULL (or even should not be defined?). How to achieve that?
     price: number | null;
}

Solution

  • You can use @Transform decorator to set price value to null

    ...
    import { Transform } from 'class-transformer';
    
    
    export class CreateItemDto {
      @IsBoolean()
      price_show: boolean;
    
      @Transform(({ value, obj }) => obj.price_show ? value : null)
      @ValidateIf((o) => o.price_show === true)
      @IsNumber()
      @Min(10)
      //TODO: if price_show is false, then price MUST BE NULL (or even should not be defined?). How to achieve that?
      price: number | null;
    }
    

    Reference