Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest.js validate array of strings if there are defined strings only

In the nest.js application on controller level I have to validate DTO.

I've faced with difficulty to check if item is not null (request should be rejected if any list item is null or undefined)

Code bellow demonstrates my configured verifications.

import { ArrayMinSize, IsArray } from 'class-validator'

export class ReminderPayload {
    // ...
    @IsArray()
    @ArrayMinSize(1)
    recipients: string[]
}

Question

  1. I'm looking for help to reject requests with body data like
{
    "recipients": [
        null
    ]
}
  1. How to validate if array items are string only (it should reject handling if object is in the array item position)?

P.S.

'class-validator' injected successfully, and it produces some validation results for my API.

like image 568
Sergii Avatar asked Aug 31 '25 15:08

Sergii


1 Answers

You need to tell class-validator to run the validations on each item of the array. Change your payload DTO to the following:

import { ArrayMinSize, IsArray, IsString } from 'class-validator';

export class ReminderPayloadDto {
  // ...
  @IsArray()
  @IsString({ each: true })  // "each" tells class-validator to run the validation on each item of the array
  @ArrayMinSize(1)
  recipients: string[];
}

Link to the docs on this.

like image 56
HMilbradt Avatar answered Sep 02 '25 20:09

HMilbradt