validation to use for api with express code example
Example 1: 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
})
Example 2: example of validating fields on your own in express
const User = require('./models/user')
exports.createUser = (req, res, next) => {
const { userName, email, phone, status } = req.body
if (userName && email && isValidEmail(email)) {
User.create({
userName,
email,
phone,
status,
})
.then(user => res.json(user))
.catch(next)
}
}