class-validator: validate number of digits for numeric values
Asked Answered
E

2

8

I'm trying to validate the number of digits for numeric values using class-validator. For example: my entity can accept only numbers of 6 digits for a given property. This way

const user1 = new User();
user1.code = 123456 // should be valid

const user2 = new User();
user2.code = 12345 // should be invalid

const user3 = new User();
user2.code = 1234567 // should be invalid

I've tried using a combination of IsNumber, MinLength and MaxLength; but not worked.

class User {
    @IsPositive()
    @IsNotEmpty()
    @IsNumber({ maxDecimalPlaces: 0 })
    @MinLength(6)
    @MaxLength(6)
    public code: number;
}  

I'm receiving a message saying that code must be shorter than or equal to 6 characters.

Can anyone help me?

Ejaculatory answered 17/2, 2022 at 14:20 Comment(0)
M
21

MinLength and MaxLength are used to check the length of a string whereas the property you are using is a number. I would suggest using Min and Max instead to check if it is a six digit number. ( @Min(100000) and @Max(999999) should do it )

Maressa answered 17/2, 2022 at 15:14 Comment(0)
B
2

Just chiming in to say you can also accomplish this with a regular expression @Matches(/^\d{6}$/).

Branum answered 6/3 at 21:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.