TypeORM与Nest.js中0/1布尔值正则验证失效问题排查
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

