When I try to initialize a validation pipe for a request body, nothing happens when an invalid type is given.
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.
import { IsString } from "class-validator";
export class TestDTO {
@IsString() public readonly string: string;
}
@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:
You can stransform your body value from boolean to number
From { "string": true } To { "string": 1 }
You can use an extra validate decorator , the @IsNotIn(values: any[])
example:
@IsString()
@IsNotIn(["FALSE", "TRUE"])
myVariable: string;
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.