Custom Input validation in nestjs

55 views Asked by At

I have the following DTO:

export class InputDTO {
  value1: string;
  value2: string:
}

I want to do validation in such a way that if value1 field is a specific value(say "toy"), then value2 should not be empty. How can I achieve this?

2

There are 2 answers

0
Lou_is On

The NestJS documentation points class-validator documentation for such customization.

Conditional validation seems to suit your need : https://github.com/typestack/class-validator#conditional-validation

Something similar to this should work:

import { ValidateIf, IsNotEmpty } from 'class-validator';

export class InputDTO {
    value1: string;

    @ValidateIf(o => o.value1=== 'toy')
    @IsNotEmpty()
    value2: string;
}
0
Hai Alison On

you will be to use class-validator:

import { IsString, ValidateIf } from 'class-validator';

export class InputDTO {
  @IsString()
  value1: string;

  @IsString()
  @ValidateIf((obj) => value1 === 'toy')
  value2: string:
}