cannot validate express post body. Error, an unknown value was passed to the validate function
Description
When i convert express post body to a class instance using class-transformer, and then try to validate it, i get the error {"unknownValue":"an unknown value was passed to the validate function"}
Minimal code-snippet showcasing the problem
import express from 'express';
import { validate } from 'class-validator';
import Product from '../models/Product.js';
import Response from '../models/Response.js';
import {plainToClass, plainToInstance} from 'class-transformer';
export async function validateProduct(req:express.Request, res: express.Response, next){
if(req.method != "GET" && req.method != "DELETE"){
console.log('product route. validating %s', req.method)
let product = plainToInstance(Product, req.body);
let errors = await validate(pd as Product,{skipMissingProperties: true,whitelist:true, forbidUnknownValues:true})
console.log('product validation errors are %s', JSON.stringify(errors));
if(errors.length > 0){
let response = new Response()
response.success = false;
response.errors = errors.map((error) => JSON.stringify(error.constraints));
res.status(400).json(response)
}else{
next()
}
}else{
next()
}
}
Expected behavior
validate the item
Actual behavior
not validating the item but returns the error above.
Hi
I had the same issue, maybe that helps: https://github.com/typestack/class-validator/issues/1474
Closing as cannot reproduce, because no minimum reproducible example was provided.
Please provide a minimal reproducible example showcasing your problem. The example should:
- be as short as possible while clearly showcasing the problem
- has no external dependencies, only this lib
- the expected and actual behavior should be explained
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.