类验证器:验证数值的位数

Bru*_*res 7 javascript typescript class-validator

我正在尝试使用 验证数值的位数class-validator。例如:我的实体只能接受给定属性的 6 位数字。这边走

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
Run Code Online (Sandbox Code Playgroud)

我尝试过使用 IsNumber、MinLength 和 MaxLength 的组合;但没有起作用。

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

我收到一条消息说code must be shorter than or equal to 6 characters

谁能帮我?

小智 17

MinLength 和 MaxLength 用于检查字符串的长度,而您使用的属性是数字。我建议使用 Min 和 Max 来检查它是否是六位数字。( @Min(100000) 和 @Max(999999) 应该这样做)