dt dino
dt dino

Reputation: 1194

express-validator with get service

I want to validate my parameters in get service.

my url is like /tableref?param1&param2

my code is like this

app.get('/tableref\?:event&:queryObject', [
check('event').isLength({ min: 5, max:15 }),
check('queryObject').isLength({ max: 5, max:35 })
] , function(req, res) {...})

But I have a 404 error.

I want to use express-validator to check my params. Before, my code was

 app.get('/tableref', function(req, res) {...})

how can I check my params with get query ? Tks

Upvotes: 1

Views: 1922

Answers (1)

dimitris tseggenes
dimitris tseggenes

Reputation: 3186

You can do it the same way you would implement it case of post or put requests.
You should just import query validator

const { query, validationResult } = require('express-validator/check');


app.get("/tableref", 
    [
        query('event').isLength({ min: 5, max:15 }),
        query('queryObject').isLength({ min: 5, max:35 })
    ],
    (req, res, next) => {
        // Check validation.
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(422).json({ errors: errors.array() });
        }
        return res.status(200).json({message:'valid query params'});

});

You url should be like this /tableref?event=example&queryObject=anotherexample

Please note that using above code, your query marameter is required. If you omit one, you will get an error.
In case you want any of your parameter to be optional you have to add the optional method

query('queryObject')
.optional({checkFalsy: true}).isLength({ min: 5, max:35 })

This way, /tableref?event=example request is pretty valid.

Upvotes: 1

Related Questions