Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use validation groups for DTOs in a NestJS controller?

I want to use validation groups in my DTO and use them in my controller. Does anyone know how you can use/pass validation groups to the controller or have the request.user automatically pass it to the controller?

create-user.dto.ts

export class CreateUserDto {
  @IsNotEmpty({
    groups: ["admin"],
  })
  role: string;

  @IsNotEmpty()
  @IsEmail()
  email: string;

  @IsNotEmpty()
  password: string;
}

users.controller.ts

@Controller('users')
@UseGuards(JwtAuthGuard)
@UseInterceptors(ClassSerializerInterceptor)
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
  ) {}

  @Post()
  async create(@Body() createUserDto: CreateUserDto): Promise<User> {
    const result = await this.usersService.create(createUserDto);
    return result;
  }
}
like image 623
NineBlindEyes Avatar asked Oct 24 '25 17:10

NineBlindEyes


1 Answers

@IsNotEmpty and @IsEmail decorators are coming from the class-validator library, so you should use ValidationPipe

Nest JS docs about validation: https://docs.nestjs.com/techniques/validation

Updated users.controller.ts:

@Controller('users')
@UseGuards(JwtAuthGuard)
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
  ) {}

  @Post()
  @UsePipes(new ValidationPipe({ groups: ["admin"] }))
  async create(@Body() createUserDto: CreateUserDto): Promise<User> {
    const result = await this.usersService.create(createUserDto);
    return result;
  }
}
like image 108
Антон Невзгодов Avatar answered Oct 27 '25 06:10

Антон Невзгодов