How to set validation correctly by regex in typeorm and nest.js

3.8k views Asked by At

I'd like to set boolean validation, it means it only permit 0 or 1.

entity.ts

  @Column('int')
  isLastdate: number;

I set above rule by following regular expression

dto.ts

const boolRegex = /^[01]$/


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

I throw following json to the api-server

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

But the response is following. Are there anything wrong with my validation ?

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

There are 2 answers

0
Somya Bansal On

Instead of type int, try going for boolean, both in your dto and entity @Column('boolean'). If you really need 0 or 1 in request, map them to boolean while saving in the database.

0
Onivaldo On

use @IsNumberString instead @IsInt