Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with ValidationPipe in NestJS when I need to validate the contents of an array

I have a situation where my client user can enter zero or multiple addresses. My problem is that if he enters an address, some fields need to be mandatory.

user.controller.ts

@Post()
@UsePipes(ValidationPipe)
async createUser(
    @Body() createUser: CreateUserDto,
) {
    return await this.service.saveUserAndAddress(createUser);
}

create-user.dto.ts

export class CreateUserDto {
    @IsNotEmpty({ message: 'ERROR_REQUIRED_FULL_NAME' })
    fullName?: string;

    @IsNotEmpty({ message: 'ERROR_REQUIRED_PASSWORD' })
    password?: string;

    @IsNotEmpty({ message: 'ERROR_REQUIRED_EMAIL' })
    @IsEmail({}, { message: 'ERROR_INVALID_EMAIL' })
    email?: string;

    ...

    addresses?: CreateUserAddressDto[];
}

create-user-address.dto.ts

export class CreateUserAddressDto {
    ...

    @IsNotEmpty()
    street: string;

    ...
}

CreateUserDto data is validated correctly and generates InternalServerErrorResponse, but CreateUserAddressDto data is not validated when there is some item in my array. Any idea how I can do this validation?

like image 640
Bráulio Figueiredo Avatar asked Dec 05 '25 13:12

Bráulio Figueiredo


1 Answers

Nest fw uses class-transformer to convert a json to a class object. You have to set the correct type for the sub-attribute if it is not a primitive value. And your attribute is an array, you have to config to tell class-validator that it is an array, and validate on each item.

Let's update CreateUserDto

import { Type } from 'class-transformer';
import { ..., ValidateNested } from 'class-validator';

export class CreateUserAddressDto {
    ...


    @ValidateNested({ each: true })
    @Type(() => CreateUserAddressDto)
    addresses?: CreateUserAddressDto[];

    ...
}

like image 198
hoangdv Avatar answered Dec 10 '25 01:12

hoangdv