7

I want to make rule by class validator, value of name's length should be min length = 1, max length = 100.

but i'm stuck during 3 days..

each value of name should be between 1-100 characters.

[{'id': 1, 'name': 'a'}, {'id': 2, 'name': '0123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678901'}]

// it's okay becuase 100 characters.

i tried, and googled so many times.. but nothing has worked fine. what should i do??

import { ApiProperty } from '@nestjs/swagger'
import { Length } from 'class-validator'
import { Column, PrimaryGeneratedColumn } from 'typeorm'
import { MaxLenPostFolderName } from './createPostFolder.dto'

class RenamePostFolder {
  @ApiProperty()
  @PrimaryGeneratedColumn()
  id: number

  @ApiProperty({ description: 'post folder name' })
  @Column({ type: 'varchar', length: MaxLenPostFolderName, nullable: false })
  // @Length(1, MaxLenPostFolderName, { each: true })
  name: string
}

// 
export class RenamePostFolderDto {
  @ApiProperty({ required: true })
  @Length(1, MaxLenPostFolderName)
  name: string
}

// created new rename dto, because spec updated, to make 'batch rename'
export class RenamePostFolderDtoV2 {
  @ApiProperty({ required: true, type: [RenamePostFolder] })
  // @Length(1, MaxLenPostFolderName)
  postFolders: RenamePostFolder[]
}

1 Answer 1

7

You can use MinLength and MaxLength

import { ApiProperty } from '@nestjs/swagger';
import { MaxLength, MinLength } from 'class-validator';

const MIN_LENGTH = 1;
const MAX_LENGTH = 100;

export class RenamePostFolderDto {
  @ApiProperty({ required: true })
  @MinLength(MIN_LENGTH)
  @MaxLength(MAX_LENGTH)
  name: string;
}

It's listed in multiple examples from class-validator's documentation on GitHub

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.