0

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;
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Was afraid I'd have to implement my own, was hoping to get something out of the box. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.