Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

npm "validator" vs "express-validator"

Tags:

node.js

npm

I am new to Node JS and haven't used any of these modules. Can I please ask for help on which of these two validators is better and more efficient to use?

validator: https://www.npmjs.com/package/validator

express-validator: https://www.npmjs.com/package/express-validator

Any help would be much appreciated. Thank you so much.

like image 239
hotchoco Avatar asked Jan 28 '23 08:01

hotchoco


1 Answers

They are used for different scenarios:

  • validator is a library to validate any kind of object and it's not associated with any framework.

  • express-validator uses validator library to validate expressjs routes. Basically you can validate express routes out of the box using validator lib.

In my honest opinion you can easily create your own validator middleware. Specially if you are new to Node.js it will help you to understand how middlewares work. If you are not interested on that and you have an express application feel free to use express-validator

Also I really recommend JOI as a validator lib https://github.com/hapijs/joi it's simple and it works well.

Here is an example of a middleware (I have not tested)

const Joi = require('joi')
module.exports = function validate(joiSchema) {
  return async (req, res, next) => {
    const result = Joi.validate(req.body, joiSchema, {
      allowUnknown: true,
      abortEarly: false
    })

    if (result.error) {
      throw new result.error
    }

    await next()
  }
}

  // express route
  router.post(
    '/create',
    validateMiddleware({
      body: {
        body: { firstName: Joi.string(), lastName: Joi.string() }
      }
    }),
    (req, res, next) => {
    // your logic
   })
like image 138
Marco Talento Avatar answered Jan 31 '23 07:01

Marco Talento