Tips on using class-validator @isArray to handle cases where only a single item is received from a query parameter

Currently, I am attempting to validate a request using class-validator to check if it is an array.

The inputs are sourced from query parameters like this: /api/items?someTypes=this

This is what my request dto resembles:

    (...)
    @IsArray()
    @IsEnum(SOMETHING, {each: true})
    readonly someTypes: keyof typeof SOMETHING[];
    (...)

When only one item is provided, the @IsArray validation returns an error, indicating that it is not an array.

I would like for it to be considered an array even when only one item is received via the query parameter, but I'm unsure of how to achieve this.


I am aware that using /api/items?someTypes[]=this will pass validation.

However, I am curious if there is an alternative method to address this issue.

Answer №1

If you have an array in your field and need to validate each item within the array, you will need to include the each: true option with the @IsEnum() decorator.

import { IsArray, IsEnum } from 'class-validator';

enum SomeType {
  A,
  B,
  C,
}

class SearchQuery {
  @IsArray()
  @IsEnum(SomeType, { each: true })
  types: SomeType[];
}


@Controller()
export class AppController {
  @Get()
  async search(@Query() searchQuery: SearchQuery): Promise<void> 
  { ... }
}

You can test this by making a GET request to your endpoint using the following syntax.

?types[]=A&types[]=B&types[]=C

This syntax works well if you only pass one item.

?types[]=A

If you would prefer a different format such as types=A,B,C, you can combine class-validator with class-tranformer.

class SearchQuery {
  @IsArray()
  @IsEnum(SomeType, { each: true })
  @Transform(({ value }) =>
    value
      .trim()
      .split(',')
      .map((type) => SomeType[type]),
  )
  types: SomeType[];
}

Answer №2

Once the each option is configured, there is no requirement to utilize @IsArray. validation-arrays

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

Managing form input in Ionic2 components from external sources in Angular2

Hello there, I am currently facing an issue with managing form validation along with proper styling for nested forms. Here's what I'm aiming to achieve: I have a Page that displays Tabs components with four tabs. Each tab represents a separate @ ...

The variable type 'editor.IStandaloneCodeEditor' does not match the parameter type 'monaco.editor.IStandaloneCodeEditor'

After installing the "monaco-editor" package using the command npm i monaco-editor, I encountered a type error in my source code. Can someone help me understand why this error is happening and how I can resolve it? This is the package file content: { "p ...

Guide on converting any object with keys of type string to a generic type

I'm grappling with a function that yields an Output generic type. In this function, I initiate an API request that responds with a json object. My aim is to have the function return this json object in the Output Generic type format Take a look at th ...

Validation for HTML5 does not appear when inputmask is used for entering mobile numbers

One problem that I have encountered is when using the input type = "text" with required = "required" for a mobile number along with an input mask. In this scenario, if a user does not enter any value, the HTML5 validation message does not appear. Instead, ...

Discover the wonders of utilizing @blur events on your custom Vue components!

Trying to create a customized component that mimics an input field with validation, I'm encountering issues with getting @Change, @blur, and other events to function properly as they would on a standard input field. This is the structure of my custom ...

I am looking for a way to transfer data collected from an input form directly to my email address without the need to open a new window. As of now, I am utilizing angular

Is there a way to send this data to my email address? I need help implementing a method to achieve this. {Name: "John", phoneNumber: "12364597"} Name: "John" phoneNumber: "12364597" __proto__: Object ...

A TypeScript class utilizing a static variable with the singleton design pattern

I have a query regarding the most effective way to code this scenario: Within a class, I require a static variable that is accessible throughout the entire project: connection Singleton without namespace: class Broker { static connection: Connection = u ...

React: The Material-UI autocomplete input, controlled with the React Hook Form `<controller>` component, experiences issues when the `multiple` prop is set to `true`

Currently facing challenges with managing an autocomplete MUI component using the <controller> component in react-hook-form. Take a look at the code snippet below: <Controller control={control} name="rooms" render={({ field }) =&g ...

Exploring the functionality of the WHERE function in Firebase with Angular

Current Objective: Our main focus here is to allow users to post within their designated Organization Group. These posts should remain exclusively visible within the specific Organization Group they are posted in. To achieve this, I have attempted to impl ...

TypeScript class featuring a unique method that is not utilized in every instance

I have a TypeScript class that is managing ZMQ bus communication. Initially, I created a general class that can be instantiated multiple times. However, now I need to create instances with slight variations that do not perfectly fit the generic class I o ...

Automatically update data in Angular without the need to refresh the page

One feature of my application involves displaying a table with rows retrieved from a database. The functionality responsible for fetching this data is an AJAX call, implemented as follows: getPosts(): Observable<Posts[]> { return this.http.post ...

Encountered an error while trying to load config.ts file because of an issue

Trying to set up a new protractor project to conduct tests on an angular site. Node.js, typescript, protractor, and jasmine are all installed globally. After running webdriver-manager update and webdriver-manager start in the project folder, I proceed to b ...

What is the best way to implement dependency injection in order to assign a validator to an entity through the IValidatableObject interface?

Within my business layer, I have objects that implement the IValidatableObject interface. My goal is to store the business rules for these entities in an external assembly and then invoke the validator for each type through this method: public IEnumerable ...

When using Sequelize, you may notice that extra spaces are automatically added at the end of the DataTypes.CHAR data type

Here is an example of how I structure my Store.ts file: import {DataTypes, Model, ModelAttributes} from "sequelize"; export default class Store extends Model { declare id: number declare name: string declare phone: string } export const S ...

Achieving VS Code/typescript autocomplete functionality without the need to import the library

When a module (for example, moment.js, knockout, or big.js) is added with a <script> tag like this: <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"> </script> that defines a global property (for instance ...

Every time an action is carried out in the app, React generates countless TypeError messages

Whenever I'm using the application (particularly when started with npm start), my console gets flooded with thousands of TypeError messages like this: This issue doesn't occur when I build the app... It's frustrating navigating through the ...

Ensuring the accuracy of the angular-formly form definition

I am currently involved in a project where users can input a JSON formly form definition that gets saved into the database. This definition will later be utilized to create a form. Before storing this JSON definition in the database, I need to validate it ...

Serve both .ts and .js files to the browser using RequireJs

In my ASP.NET Core Project, the following files are present: greet.ts export class WelcomMesssage { name: string; constructor(name: string) { this.name = name; } say(): void { console.log("Welcome " + this.name); } } GreetExample.ts import * as ...

How should one properly format an array of objects with elements that are different types of variations?

I am currently developing a versatile sorting module using TypeScript. This module will take in an array of data objects, along with a list of keys to sort by. Once the sorting process is complete, the array will be sorted based on the specified keys. To ...

Using getters in a template can activate the Angular change detection cycle

When using getters inside templates, it seems that Angular's change detection can get stuck in a loop with the getter being called multiple times. Despite researching similar issues, I have not been able to find a clear solution. Background info: I ...