Giter Site home page Giter Site logo

Comments (4)

seanpmaxwell avatar seanpmaxwell commented on August 14, 2024

With express-validators, isn't it done more like check('something').not().isEmpty(). I think body('time').exists({checkNull: true}) is checking to see if it is null. I'm not sure though cause I haven't used express-validators before.

from overnight.

jmpmscorp avatar jmpmscorp commented on August 14, 2024

Thanks for reply @seanpmaxwell.

I just try your suggestion but again any error is thrown if my body is empty. Now, my controller looks like:

@Controller('vehicle/:vehicle_id/engine')
@ClassOptions({mergeParams: true})
export class VehicleEngineController {

    @Post()
    @Middleware(check('time').not().isEmpty())
    private async insertData(req: Request, res: Response) {
        return res.status(200).send(`Receive Data from Vehicle ${req.params.vehicle_id}`);
    }
}

However, If I code my own validator function and pass through @Middleware, it works perfectly. I don't know if, maybe, there is any problem with express-validator and annotations.

Thank you.

from overnight.

AnandChowdhary avatar AnandChowdhary commented on August 14, 2024

This isn't related to express-validator, but I'm using a custom validator like this, in case it helps:

@Controller("users")
export class UserController {
  @Put()
  @Middleware(
    validator(
      {
        name: Joi.string(),
        email: Joi.string().required()
      },
      "body"
    )
  )
  async put(req: Request, res: Response) {
    res
      .status(CREATED)
      .json({ success: true, message: "user-created" });
  }
}

The above example validates req.body and uses the following validator middleware:

import { Request, Response, NextFunction } from "express";
import Joi from "@hapi/joi";
export const validator = (
  schemaMap: Joi.SchemaMap,
  type: "body" | "params" | "query"
) => {
  return (req: Request, res: Response, next: NextFunction) => {
    let data: any;
    switch (type) {
      case "params":
        data = req.params;
        break;
      case "query":
        data = req.query;
        break;
      default:
        data = req.body;
        break;
    }
    const schema = Joi.object().keys(schemaMap);
    const result = Joi.validate(data, schema);
    if (result.error) throw new Error(`joi:${JSON.stringify(result.error)}`);
    next();
  };
};

from overnight.

seanpmaxwell avatar seanpmaxwell commented on August 14, 2024

Hey man sorry for the late response but I think you using express validators wrong. You forgot this line
validationResult(req).throw();. I added an example to the sample-project and it's working fine.

    @Get('debug/express-validators')
    @Middleware(check('name').exists())
    private async practiceValidators(req: Request, res: Response) {
        try {
            validationResult(req).throw();
            return res.status(OK).json({
                message: 'Hello from NodeJS ' + req.body.name,
            });
        } catch (err) {
            Logger.Err(err, true);
            return res.status(BAD_REQUEST).json({
                error: err.message,
            });
        }
    }

from overnight.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.