class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

question: array of numbers with null values

Open BUONJG opened this issue 1 year ago • 1 comments

How to validate an array of numbers where null is allowed?

I have the following command:

export class MyCommand {
    @IsNotEmpty()
    @IsArray()
    @IsNumber(undefined, { each: true })
    @ArrayMaxSize(2)
    public thicknessRange: number[] = [];
}

I want to allow in thicknessRange property any of those values:

  • [1, 2] => OK
  • [1] => OK
  • [null, 2] => Not OK as null is not a number!

The problem: I don't see any way to allow null in my array of numbers. Usually, in order to allow null on a number, I add @IsOptional() decorator but in this case it make the entire array optional and it is not what I want. I tried with @IsOptional({ each: true }) but it didn't work...

BUONJG avatar May 06 '24 15:05 BUONJG

I think resolving this issue with your current approach might be difficult. This is because you are using IsNumber rules, which validate that each item in the array is a number. I believe creating custom rules would be necessary to address your concerns.

ytetsuro avatar May 09 '24 10:05 ytetsuro