Home > Enterprise >  NestJs - Ignore Class validation in Class Validator
NestJs - Ignore Class validation in Class Validator

Time:02-14

I have a DTO. I need to validate user entries against some strings . Those values are coming from ENV file. I got it to work, but I also need to ignore the case.

This is the value from the env file:

SEARCH_BY_LANGUAGE="Java,Javascript"

This is my version where it works, but it is sensitive to cases:

@Expose()
@IsNotEmpty()
@ApiProperty()
@IsIn(process.env.SEARCH_BY_LANGUAGE.toLowerCase().split(","))
targetLanguage: string

Problem with this approach is that, java and Java are treated differently.

I have tried to use the @Matches, like this:

@Expose()
@IsNotEmpty()
@ApiProperty()
@Matches(`^${process.env.SEARCH_BY_LANGUAGE.split(",")}$`, 'i')
targetLanguage: string

But I am getting this error:

[ExceptionsHandler] Invalid flags supplied to RegExp constructor '^Java,Javascript$' 14493m

I feel I am close, but cant figure it out.

CodePudding user response:

You have two possible approaches for that, the first one is @Transform() decorator from class-transformer, like Jay McDoniel commented above:

You can perform additional data transformation using @Transform decorator. For example, you want to make your Date object to be a moment object when you are transforming object from plain to class:

import { Transform } from 'class-transformer';
import * as moment from 'moment';
import { Moment } from 'moment';

export class Photo {
 id: number;

 @Type(() => Date)
 @Transform(({ value }) => moment(value), { toClassOnly: true })
 date: Moment;
}

Now when you call plainToClass and send a plain representation of the Photo > object, it will convert a date value in your photo object to moment date. @Transform decorator also supports groups and versioning.

So you would do something like this:

@Transform((value) => value.toLowerCase() })
 targetLanguage: string

Your second approach would be to use a NestJS custom interceptor and manually change your payload/data before using it

  • Related