Validate information coming in req

Asked

Viewed 104 times

0

I receive information for my route, where they are contained within a req. Ex:

router.post('/', function (req, res){

});

This information I will put in my bank, however, before entering, I have to check if really came all the information, because if not, there will be an exception as I would try to enter information of fields that do not exist.

I would like to know how I can validate these fields. For example, I use:

if (req.body['name']) {
     console.log('Nome foi enviado com sucesso!');
}

But doing this for all fields sent makes things more difficult, I wonder if Nodejs provides some easier and more efficient way to do this.

  • This may help: https://www.npmjs.com/package/validator

  • What do you do in case you don’t validate? send it back? If you want to do a simple validation it would be enough var valido = Object.keys(req.body).filter(k => !req.body[k]).length == 0; (is an example, certainly needs to fine tune, but it would be very simple)

  • Good, @ I will need something similar to validate email and phone, this library can help.

  • Yes @Sergio, if any data does not arrive, I will send a res.status(x); I know that the front end will certainly make a validation if some field has not been filled in, besides, if I try to insert something that did not come in the bank, will give exception, and the server will fall, to make it safer, by way of doubt, I also want to do.

  • Good, and you should. If you use that library and give the right names to the data keys you pass you can greatly simplify the implementation. 'Cause you can use it in a loop validator.is[chave]('[email protected]');

  • Can you answer an example of how the loop would look using this library ? As an example you can use fields like nome,telefone,email,endereço. @Sergio

  • Complementing Miguel’s tip you can use the Express Validator that uses the Validator lib behind, but that works a little more integrated as express.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.