Ejemplo 1: validador express
// this method create custom express validator using middleware
const { validationResult, check } = require('express-validator')
exports.resultsValidator = (req) => {
const messages = []
if (!validationResult(req).isEmpty()) {
const errors = validationResult(req).array()
for (const i of errors) {
messages.push(i)
}
}
return messages
}
exports.registerValidator = () => {
return [
check('username')
.notEmpty()
.withMessage('username is required')
.not()
.custom((val) => /[^A-za-z0-9s]/g.test(val))
.withMessage('Username not use uniq characters'),
check('password')
.notEmpty()
.withMessage('password is required')
.isLength({ min: 8 })
.withMessage('password must be 8 characters')
]
}
exports.loginValidator = () => {
return [
check('username').notEmpty().withMessage('username or email is required'),
check('password').notEmpty().withMessage('password is required')
]
}
// how to use express validator in controller for results message
const errors = resultsValidator(req)
if (errors.length > 0) {
return res.status(400).json({
method: req.method,
status: res.statusCode,
error: errors
})
}
// how to use express validator in route
route.post('/login', loginValidator(), (req, res) => {
return res.status(200).send('Login Sucessfuly');
});
route.post('/register', registerValidator(), (req, res) => {
return res.status(200).send('Register Sucessfuly');
});
Ejemplo 2: validador express
npm install --save express-validator
Ejemplo 3: ejemplo de validación de campos por su cuenta en express
const User = require('./models/user')
exports.createUser = (req, res, next) => {
/** Here you need to validate user input.
Let's say only Name and email are required field
*/
const { userName, email, phone, status } = req.body
if (userName && email && isValidEmail(email)) {
// isValidEmail is some custom email function to validate email which you might need write on your own or use npm module
User.create({
userName,
email,
phone,
status,
})
.then(user => res.json(user))
.catch(next)
}
}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)