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)
You can provide the regex:
router.get('/:id(\\d+)/', function (req, res, next){
// body
});
Docs
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' });
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With