Home > Software engineering >  class-validator: validate number of digits for numeric values
class-validator: validate number of digits for numeric values

Time:02-18

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?

CodePudding user response:

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 )

  • Related