How to validate request body in Node.js, Express - is it possible without using a library?
Asked Answered
R

5

13

I have the code (below) and one developer said to me that I had to validate my request:

router.post('/dashboard', passport.authenticate('jwt', { session: false }),
(req, res) => {

    try {
        let newPost = new Post({
            category: req.body.category,
            title: req.body.title,
            photo: req.body.photo,
            text: req.body.text,
            author: req.body.author,
            date: req.body.date
        });

        Post.addPost(newPost, (err, user) => {
            if (err) {
                res.json({success: false, msg: `Post has not been added. ${err}`})
            } else {
                res.json({success: true, msg: 'Post was added.'})
            }
        })
    } catch (err) {
       const error = (res, error) => {
            res.status(500).json({
                success: false,
                message: error.message ? error.message : error
            })
       }

       console.log('error routes/auth POST', res, error)
    }
})

I googled and found the solutions i.e. using libraries for request validation like express-validator - is it ok?

Are there any native, built-in express, node.js methods to validate a request?

Or it's better to use a library like express-validator?

Rickettsia answered 7/12, 2021 at 7:8 Comment(1)
Can recommend Joi, but express-validator is also ok. It's much better than write your own validators.Verdugo
W
32

Express.js doesn't have a built-in validator. But you can use express-validator or joi. Both of these libraries are good.

if you are using typescript in your project class-validator is a better option, it will let you use types.

And this is a great talk on why you need to validate the data. Take Data Validation Seriously by Paul Milham

Winchell answered 7/12, 2021 at 8:34 Comment(0)
P
2

This is a bit late! Unfortunately, ExpressJs does not have build-in validation. You can use Zod to validate your request's (params, query or body) payloads by creating a custom middleware or use a package like zod-express-middleware

Pacifically answered 14/1, 2023 at 21:39 Comment(0)
B
1

As mentioned above Express.js does not have its own built-in validator. You can also check this library simple-body-validator, it offers an experience similar to the Laravel validation

Boxboard answered 21/6, 2022 at 8:26 Comment(0)
D
0

We can use Yup for Express Validation: https://github.com/jquense/yup

Example:

import * as yup from 'yup'

const userCreateSchema = yup.object({
  email: yup.string().email().required(),
  password: yup.string().required(),
})
const result = await userCreateSchema.validate(req.body)
Deceive answered 11/6, 2023 at 3:12 Comment(0)
R
0

If you want to provide an openapi/swagger file to publish how to use your api, and have your service validate against the models in the spec then I recommend using openapi-backend

Reichel answered 27/3 at 3:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.