简体   繁体   中英

Cannot get ValidatorPipe to work with nest.js

Current behavior

When I try to initialize a validation pipe for a request body, nothing happens when an invalid type is given.

Expected behavior

When the user specifies a value that goes against the type in my DTO, I reject with an error. In this case, I request /test with a body of

{ "string": true }

I expect this to error but it does not.

Minimal reproduction of the problem

Test DTO

import { IsString } from "class-validator";
export class TestDTO {
  @IsString() public readonly string: string;
}

Test Controller

@Controller()
export class TestController {
  @Post("/test")
  public testing(@Body(new ValidationPipe()) test: TestDTO): string {
    return test.string;
  }
}

When the body contains boolean, the backend (nestjs) parse it as a string There is a decorator to validate if parameter has boolean as a string

@IsBooleanString()
myVariable:boolean;

What you can do in your case:

  • Option 1

You can stransform your body value from boolean to number

From { "string": true } To { "string": 1 }
  • Option 2

You can use an extra validate decorator , the @IsNotIn(values: any[]) example:

@IsString()
@IsNotIn(["FALSE", "TRUE"])
myVariable: string;
  • Option 3

You can create your own decorator

import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';

export function IsNotBoolean(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'IsNotBoolean',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
         if(value.toUpperCase() == 'TRUE' || value.toUpperCase() == 'FALSE'){
          return false
         } else {
          return true
         }
        },
      },
    });
  };
}

On the DTO

import { IsString } from "class-validator";
import { IsNotBoolean } from "the path of your custom validate decorator"

export class TestDTO {
  @IsString({myErrorKey:'My error message'}) 
  @IsNotBoolean({the optional error message object})
  string: string;
}

On the Controller

public testing(@Body(ValidationPipe) test: TestDTO): string {
    return test.string;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM