Class-validator: eliminate a field during validation depending on the value of another field

When using class-validator in conjunction with NestJS, I have successfully implemented the following:

export class MatchDeclineReason {
  @IsString()
  @IsEnum(MatchDeclineReasonType)
  @ApiProperty()
  type: MatchDeclineReasonType;

  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
  @IsString()
  @ApiProperty()
  freeText: string;
}

In this setup, if declineReason.type === Other, I would like to receive a value for freeText as a string.


Conversely, if declineReason.type is anything other than Other, I want the freeText property to be removed completely.

My goal is to achieve this behavior without resorting to writing a CustomValidator. Is there any way to do so?

This is how my ValidationPipe is configured:

  app.useGlobalPipes(
    new ValidationPipe({
      disableErrorMessages: false,
      whitelist: true,
      transform: true,
    }),
  );

Answer №1

To accomplish this, implement a unique algorithm for converting values:

  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
  @Transform((params) =>
    (params.obj.type === MatchDeclineReasonType.Other ? params.value : undefined)
  )
  @IsString()
  @ApiProperty()
  customText: string;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to start the Azure Functions within a Nodejs Monorepo, the runtime fails with an error

My setup involves a nodejs typescript monorepo structured as follows: libraries/ lib1/ lib2/ package.json tsconfig.json web-api/ function1/ function.json index.ts function2/ function.json index.ts host.json package.json ts ...

Exploring/Adjusting an RxJS Observable Object

I'm currently working with a typescript method that looks like this: private processRequest<T>(request: Observable<T>, ...): Promise<T> {...} request is an HttpClient Observable processRequest(httpClient.get(url, ...)); ... processR ...

What could be the root of this Typescript error related to the SX prop?

I found this code snippet on https://mui.com/system/the-sx-prop/ and tried implementing it, but encountered a TypeScript error. sx={(theme: Theme): SxProps<Theme> | undefined => ({ ...theme.typography.body, color: theme.palette.primary.main, ...

Encountering 'no overload matches this call' while developing a useReducer using React with Typescript

import { useCallback, useReducer } from "react"; const ARTIST_REDUCER_TYPES = { ADD: "ADD", }; const artistArray = [...Object.values(ARTIST_REDUCER_TYPES)] as const; type ActionReturnedTypes = (typeof artistArray)[number]; type Re ...

Validating JSON data with REST assured

When it comes to validating Json Objects, I rely on https://code.google.com/p/rest-assured/wiki/Downloads?tm=2. import static com.jayway.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; import static org.hamcrest.MatcherAssert.asse ...

What methods can I utilize from Google Maps within Vuex's createStore()?

Currently, I am in the process of configuring my Vuex store to hold an array of Marker objects from the Google Maps Javascript API. Here is a snippet of how my createStore function appears: import { createStore } from "vuex"; export default ...

What is the best method for showing the name of the card?

I have developed a game using Angular that displays images of cards, but I am facing an issue in showing their names on the screen. At times, it displays the same name for all the cards or even incorrect names. In my TypeScript class 'Paquet', I ...

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

Should I be using this method to perform validation on floating point inputs?

After conducting thorough research on input validation techniques, I have devised a solution by incorporating various ideas. Here is the implementation: Function to verify if a string contains a valid double... bool isDouble(double& destination, stri ...

Using pipes to filter JSON data based on key value pairs

I have a collection of items in the specified structure: { img: './app/images/codeeval.png', title: 'CodeEval', repository: 'https://github.com/Shooshte/CodeEval', description: ...

Compilation error occurred when running Angular with mat-form: ngcc encountered an issue while processing [email protected]

Currently dealing with a compile error in a small mat-form example that I created. Unfortunately, I am unable to pinpoint the exact issue causing this error. If you have a moment, please take a look at the code here: https://stackblitz.com/edit/angular-iv ...

The deno bundle operation failed due to the absence of the 'getIterator' property on the type 'ReadableStream<R>'

When attempting to run deno with bundle, an error is encountered: error: TS2339 [ERROR]: Property 'getIterator' does not exist on type 'ReadableStream<R>'. return res.readable.getIterator(); ~~~~~~~~~~~ ...

Is it normal that aws-eventbridge-lambda does not generate a Lambda function?

I've been experimenting with the AWS CDK (Typescript) to enhance my knowledge. I'm interested in setting up a lambda function to run daily at a specific time or at intervals of N minutes. Since I anticipate having multiple functions, it would be ...

The types 'X' and 'string' do not intersect

I have a situation where I am using the following type: export type AutocompleteChangeReason = | 'createOption' | 'selectOption' | 'removeOption' | 'clear' | 'blur'; But when I try to compress the cod ...

Models in Typescript that are interrelated with Loopback

I'm currently working on defining connected models including the HasMany relationship in the context of @types/loopback definitions My approach involves creating an interface for HasMany and its implementation: interface IHasMany { /** ...

How to Animate the Deletion of an Angular Component in Motion?

This stackblitz demonstration showcases an animation where clicking on Create success causes the components view to smoothly transition from opacity 0 to opacity 1 over a duration of 5 seconds. If we clear the container using this.container.clear(), the r ...

Error: The next.config.js file contains invalid options - The root value includes an unexpected property

I recently updated my next version from 10 to 12, and when I run the local development server, I encounter the following error in the terminal. As a result, the code fails to compile. How can I fix this issue? Invalid next.config.js options have been iden ...

What is the proper way to tap into the features provided by DefinitelyTyped in typescript?

While working on my Angular2 app that deals with money amounts, I decided to use dinero.js to handle money values. However, I am encountering difficulties in accessing certain features in Typescript. Following the instructions, I installed the DefinitelyT ...

Obtain the roster of channels on Discord version 14

I'm struggling to retrieve the channels list of my guild using discord14 API In my previous code (discord13), I was successfully able to fetch them with this snippet const guild = bot.guilds.cache.get(GUILD_ID) const channels2 = guild.channels.c ...

I'm having trouble resolving this error that keeps popping up on this particular line of code: "registrationForm : FormGroup;" Can anyone help me troubleshoot this

***Issue: src/app/r-form-example/r-form-example.component.ts:11:3 - error TS2564: Property 'registrationForm' lacks an initializer and is not definitely set in the constructor. An error has been detected in the code snippet above. import { Comp ...