#How do I validate an array of enums using class validator?

9 messages · Page 1 of 1 (latest)

brittle halo
#

Hey all, I'm new to NestJS and having an issue when trying to validate an array of enums using class validator in my DTO. The enum has a structure like this:

export class Tag {
static readonly ANGULAR = new Tag('Angular', 'red');
static readonly TYPESCRIPT = new Tag('TypeScript', 'darkblue');
static readonly NODEJS = new Tag('NodeJS', 'green');

private constructor(
private readonly key: string,
public readonly color: string,
) {}

toString() {
return this.key;
}
}

and my DTO looks like this:

import { IsString, IsArray } from 'class-validator';
import { Tag } from '../models/tag.enum';

export class CreateProjectDto {
@IsString()
name: string;

@IsString()
summary: string;

@IsString()
description: string;

@IsString()
projectLink: string;

@IsArray()
images: string[];

@IsArray()
tags: Tag[];
}

However when I use this DTO in my service for my create method which looks like this:

create(createProjectDto: CreateProjectDto) {
return this.prisma.project.create({
data: createProjectDto,
});
}

it comes up with an error for the data property which is attached.

Any help would be appreciated, thanks!

brittle halo
#

Thanks for your response, my latest attempt is this but it still displays the same error:

@IsArray()
@ArrayNotEmpty()
@IsEnum({ each: true })
tags: Tag[];

steel chasm
#

Hi ! I tried in local, your two class, there is no error. I think it's more related to your prisma object, not your Dto..
The Tag and the createProjectDto are working fine tgt.

Your error is: Tag[] is not Assignable to Tag[] | ProjectCreateTagsInput Do you have another class ProjectCreateTagsInput ? If yes I guess in your dto you might want to do :

export class CreateProjectDto
  @IsArray()
  tags: Tag[] | ProjectCreateTagsInput;
}
brittle halo
#

Thanks for your help, in the end my code editor seemed to like this with the Prisma object imported:

@IsArray()
@ArrayNotEmpty()
tags: Prisma.ProjectCreatetagsInput;

steel chasm
#

Hi you're welcome ! but my advice would be, don't used Prisma.ProjectCreateTagsInput in your Dto. You're mixing the DTO (data transfer object) with your PrismaModel :/ it's doesn't respect the clean architecture pattern. you're mixing the business with your DB : /

brittle halo
#

OK I understand, unfortunately if I put in tags: Tag[] | ProjectCreateTagsInput; it says it can't find ProjectCreateTagsInput. If I put in any[] it works but that doesn't feel like a good solution.

brittle halo
#

In the end I gave up and am using an array of strings now in the tags that I will convert in the frontend

steel chasm
#

would you mind showing me a bit more of your code ? schemaa / dto etc ? If I can help you I'll gladly test on my local env