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.
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With