NestJS DTO validation error 'ValidationPipe: an unknown value was passed to the validate function'
I was playing with a small test project in NestJS, and wanted to add a DTO, but came across an error that is easy to solve.
If you see the following error in NestJS when adding a DTO with validation:
"ValidationPipe: an unknown value was passed to the validate function"
Then I might have a fix for it!
This is how I had things set up:
// ... (a controller)
@Post('some-url')
@UsePipes(ValidationPipe)
public async someEndpoint(
@Body() dto: MyCustomDto
) {
return true
}
// ...
and the DTO:
export class MyCustomDto {
someNewTitle: string
}
But I was getting an ValidationPipe: an unknown value was passed to the validate function error.
It was a bit tricky to instantly debug - there was no more output about the error, and even debugging by looking at the nestjs framework JS files didn't help.
The reason was because the DTO didn't actually have any validation rules.
Changing the DTO to something like this fixed it:
import {IsString} from "class-validator";
export class MyCustomDto {
@IsString()
someNewTitle: string
}
You just have to add at least one validation check to your DTOs in nestjs.
This was a test project - in a real project its probably a big issue if you are not validating the inputs. You should configure your nestjs app with the ValidationOptions. forbidUnknownValues
, forbidNonWhitelisted
& whitelist
are useful. For debugging adding a custom exceptionFactory
also helped a little.