如何通过Typeorm和nest.js中的正则表达式正确设置验证

问题描述

我想设置boolean验证,这意味着它仅允许0 or 1

entity.ts

  @Column('int')
  isLastdate: number;

我通过遵循regular expression

设置了上述规则

dto.ts

const boolRegex = /^[01]$/


  @IsNotEmpty()
  @IsInt()
  @Matches(boolRegex,{
    message:`isLastdate must be bool (0 or 1)`
  })
  isLastdate: number;

我跟随json到api服务器

{
"userId":1,"title":"mytest","date":"2000-12-31","isLastdate":1,"beginTime":"11:59","endTime":"23:40","place":"Tokyo","labelCd":1
}

但是响应如下。 我的验证有什么问题吗?

{
    "statusCode": 400,"message": [
        "isLastdate must be bool (0 or 1)"
    ],"error": "Bad Request"
}

解决方法

而不是int类型,请尝试在dto和实体中都使用布尔值 @Column('boolean')。 如果您的请求中确实需要0或1,则在将它们保存到数据库时将它们映射为boolean。

,

使用@IsNumberString 代替@IsInt