5

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)

2 Answers 2

4

You can provide the regex:

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

Docs

Sign up to request clarification or add additional context in comments.

Comments

3

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' });
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.