class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

cannot validate express post body. Error, an unknown value was passed to the validate function

Open EdijaeCrusar opened this issue 3 years ago • 1 comments

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.

EdijaeCrusar avatar May 30 '22 21:05 EdijaeCrusar

Hi

I had the same issue, maybe that helps: https://github.com/typestack/class-validator/issues/1474

Thomas-1985 avatar Jun 20 '22 20:06 Thomas-1985

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

NoNameProvided avatar Dec 09 '22 19:12 NoNameProvided

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.

github-actions[bot] avatar Jan 09 '23 00:01 github-actions[bot]