Tatyana Molchanova
Tatyana Molchanova

Reputation: 1603

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

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?

Upvotes: 15

Views: 54961

Answers (5)

TemporaryFix
TemporaryFix

Reputation: 2196

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

Upvotes: 0

kollein
kollein

Reputation: 406

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)

Upvotes: 0

Smaiil
Smaiil

Reputation: 147

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

Upvotes: 3

Jad Khoury
Jad Khoury

Reputation: 41

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

Upvotes: 1

David
David

Reputation: 864

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

Upvotes: 34

Related Questions