Luke
Luke

Reputation: 774

Conditionally failing validation using class-validator

Using conditional validation in the class-validation library and the example below, I want the validation to fail if the woodScrews property is given a value when the tool property is Tool.TapeMeasure. I wasn't really able to find anything that does that.

import { IsEnum, IsNumber, Min, ValidateIf } from 'class-validator'

export enum Tool {
  Drill = 'Drill',
  TapeMeasure = 'Tape Measure'
}

export class ToolBox {
  @IsEnum(Tool)
  public tool: Tool;

  @ValidateIf(toolBox => toolBox.tool === Tool.Drill)
  @IsNumber()
  @Min(5)
  public woodScrews?: number;
}

Upvotes: 0

Views: 889

Answers (1)

Juan Rambal
Juan Rambal

Reputation: 629

That method only works to ignore validations i.e with your dto, you validate that the class ToolBox has a property woodScrews of type number and with a minimun value of 5 only if the property Tool is equals to Drill otherwise you'll ignore the validations.

I'm not sure if you can solve this with class-validator but you can create some customs pipes and apply your own logic.

More info here: https://docs.nestjs.com/pipes

Upvotes: 1

Related Questions