Bruno Peres
Bruno Peres

Reputation: 16375

class-validator: validate number of digits for numeric values

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?

Upvotes: 8

Views: 18156

Answers (2)

Lucas
Lucas

Reputation: 53

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

Upvotes: 3

Sandil Ranasinghe
Sandil Ranasinghe

Reputation: 768

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 )

Upvotes: 22

Related Questions