node js express validator code example
Example 1: express validator
npm install --save express-validator
Example 2: express-validator
const { body, validationResult } = require('express-validator');
app.post('/user', [
body('username').isEmail(),
body('password').isLength({ min: 5 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password
}).then(user => res.json(user));
});
Example 3: express validator
app.post('/form', [
check('name').isLength({ min: 3 }),
check('email').isEmail(),
check('age').isNumeric()
], (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() })
}
const name = req.body.name
const email = req.body.email
const age = req.body.age
})