You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM与Nest.js中0/1布尔值正则验证失效问题排查

Why Your isLastdate Validation Is Failing

Ah, I see the issue here! Let's break down why your validation is throwing that 400 error, even when you send isLastdate: 1:

The Root Cause

The @Matches validator from class-validator is designed to work with string values by default. Your DTO defines isLastdate as a number type, so when the request sends a numeric 1, the validator tries to run the regex /^[01]$/ against the number itself—not its string representation. Since a number doesn't match a regex meant for strings, the validation fails every time.

Fixes to Try

1. Use @IsIn (Recommended)

This is the cleanest solution for validating numeric values that can only be 0 or 1. The @IsIn validator checks if the value exists in a specified array, which is perfect for this boolean-like numeric use case:

import { IsNotEmpty, IsInt, IsIn } from 'class-validator';

export class YourDtoName {
  // ... your other fields
  @IsNotEmpty()
  @IsInt()
  @IsIn([0, 1], { message: 'isLastdate must be bool (0 or 1)' })
  isLastdate: number;
}

This directly validates that the numeric value is either 0 or 1, no regex hoops to jump through.

2. Adjust for String Matching (Not Recommended)

If you absolutely need to use regex, you'll need to convert the numeric value to a string before validation. You can do this with @Transform from class-transformer:

import { IsNotEmpty, Matches, Transform } from 'class-validator';
import { TransformFnParams } from 'class-transformer';

export class YourDtoName {
  // ... your other fields
  @IsNotEmpty()
  @Transform(({ value }: TransformFnParams) => String(value))
  @Matches(/^[01]$/, { message: 'isLastdate must be bool (0 or 1)' })
  isLastdate: string;
}

Note that with this approach, you'll have to convert the string back to a number before saving it to your entity (since your entity.ts defines it as number). This adds unnecessary complexity, so stick with @IsIn if possible.

Quick Recap

The regex approach fails because it's meant for strings, but your field is a number. @IsIn is purpose-built for this exact scenario of validating values against a fixed set of options.

内容的提问来源于stack exchange,提问作者Heisenberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:37:29