class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

fix: ValidateNested is effect my request.body

Open jack5341 opened this issue 2 years ago • 0 comments

Description

I was just trying update my element by UPDATE and validate inputs with class-validator. The problem is even though I'm sure that validation is a match with my body.

My request looks like this.

{
     articleNumber: '293213'
     prices: [{ price: 100, fromQuantity: 1, toQuantity: 10 }]
}

What I got.

{
     articleNumber: '293213'
     prices: [ {} ]
}

So article is updating but my pricing is also updating wrongly.

Minimal code-snippet showcasing the problem

My dto.ts file


export class CreateProductlineDto {
  @IsNotEmpty()
  @IsString()
  articleNumber: string;

  @IsOptional()
  @IsArray()
  // THE PROBLEM IS HERE !!!!
  // IF I REMOVE THE @ValidateNested() I GET INPUTS OF REQUEST.BODY
  // BUT I DONT GET THE VALIDATION ERRORS EG. YOU CAN GIVE NEGATIVE NUMBER !!!
  @ValidateNested({ each: true })
  @Type(() => Price)
  prices?: Price[];

If i remove ValidateNested() i see my request like how it is (prices: [{ price: 100, fromQuantity: 1, toQuantity: 10 }]) in otherwise its seems like prices: [ {} ]

But then I can't validate inputs with the Price item

export class Price {
  @IsNumber()
  @IsPositive()
  fromQuantity: number;

  @IsOptional()
  @IsNumber()
  @IsPositive()
  toQuantity?: number;

  @IsNumber()
  @IsPositive()
  price: number;
}

So they are not working if I remove ValidateNested().

Expected behavior

My inputs will validate by chosen properties and it shouldn't be prices: [ {} ] because my database also saves like that, so it's going to be null.

Actual behavior

Even I send body like this prices: [{ price: 100, fromQuantity: 1, toQuantity: 10 }] after validating its saving as prices: [ {} ] to database. but If I remove ValidateNested() its saving with true types but of course without validation.

jack5341 avatar May 10 '22 13:05 jack5341