Import check and body from express-validator/check
This is the route for signup POST
In authController import
const { check, body } = require('express-validator/check');
router.post('/signup',
[
check('email')
.isEmail().withMessage('Please enter a valid email.')
.custom((value, { req }) => {
return User.findOne({
email: value
}).then(user => {
if (user) {
return Promise.reject('This email is already registered. Try logging in!');
}
});
})
.normalizeEmail(),
body('password', '')
.isLength({min: 6}).withMessage('Password must be of at least 6 characters.')
.isAlphanumeric().withMessage('Only letters and digits are allowed in password.')
.trim(),
body('confirmPassword')
.trim()
.custom((value, { req }) => {
if (value === req.body.password) {
return true;
} else {
throw new Error('Password and Confirm Password do not match.');
}
}),
body('name', 'Please enter a valid name.')
.isLength({ min:3, max: 50 })
.isAlpha()
.trim()
],
authController.postSignup);
In authController import
const { validationResult } = require('express-validator/check');
Then store it in errors variable
const errors = validationResult(req);
errors has an array of errors which can be accessed in the following form and passed to frontend if required.
const validationErrors = errors.array();
Access first error in the following way
const validationFirstError = errors.array()[0].msg;
That is it. This is the way to get errors from validation middleware and display in frontend.
Comments
Post a Comment