【问题标题】:How to set validation correctly by regex in typeorm and nest.js如何通过 typeorm 和 nest.js 中的正则表达式正确设置验证
【发布时间】:2021-01-15 02:35:47
【问题描述】:

我想设置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-server

{
"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"
}

【问题讨论】:

  • 不确定是否需要通过 @Column('int') 。改用@Column()
  • 我改了@Column(),但还是有错误。

标签: regex typescript typeorm class-validator


【解决方案1】:

使用@IsNumberString 代替@IsInt

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2012-01-08
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2015-04-20
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多