Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Express.js URL parameters validation

I'm a node.js/express.js newbie. How can I validate :id parameters? I would like to pass only numbers into :id parameters. If :id is a string or contain once of them, I would to display a 404 error like a zend framework routing http://framework.zend.com/manual/current/en/user-guide/routing-and-controllers.html

/routes/users.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/:id?/', function(req, res, next) {
  var id = req.params.id;
  if(id){
    res.render('single-users', { title: 'Single ' + id });
  }else {
    res.render('users', { title: 'All users' });
  }

});

module.exports = router;

I tried to change

router.get('/:id?/', function(req, res, next)

to

router.get('/[0-9]+?/', function(req, res, next)

but

localhost:3000/users/ab/

works and display single-users page and I want it..

SOLUTION SUGGESTED BY LUCAS COSTA

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/:id(\\d+)?/', function(req, res) {
  var id = req.params.id;

  if(id){
    res.render('single-users', { title: 'Single ' + id });
  }else {
    res.render('users', { title: 'All users' });
  }

});

module.exports = router;

or

router.get('/:id([0-9]+)?/', function(req, res)
like image 434
Alessandro Corradini Avatar asked Mar 16 '16 17:03

Alessandro Corradini


2 Answers

You can provide the regex:

router.get('/:id(\\d+)/', function (req, res, next){
    // body
});

Docs

like image 190
BrTkCa Avatar answered Oct 02 '22 22:10

BrTkCa


Why not just do the integer-only check inside of the main code block and then return the 404 conditionally?

router.get('/:id', function(req, res, next) {
  var id = req.params.id;
  if(id && string.match(/^[0-9]+$/) != null)}
    res.render('single-users', { title: 'Single ' + id });
  }else if(string.match(/^[0-9]+$/) == null){
    res.status(404).render('your-404-view');
  }else{
    res.render('users', { title: 'All users' });
  }
});
like image 33
Ameo Avatar answered Oct 03 '22 00:10

Ameo