1// this method create custom express validator using middleware
2
3const { validationResult, check } = require('express-validator')
4
5exports.resultsValidator = (req) => {
6 const messages = []
7 if (!validationResult(req).isEmpty()) {
8 const errors = validationResult(req).array()
9 for (const i of errors) {
10 messages.push(i)
11 }
12 }
13 return messages
14}
15
16exports.registerValidator = () => {
17 return [
18 check('username')
19 .notEmpty()
20 .withMessage('username is required')
21 .not()
22 .custom((val) => /[^A-za-z0-9\s]/g.test(val))
23 .withMessage('Username not use uniq characters'),
24 check('password')
25 .notEmpty()
26 .withMessage('password is required')
27 .isLength({ min: 8 })
28 .withMessage('password must be 8 characters')
29 ]
30}
31
32exports.loginValidator = () => {
33 return [
34 check('username').notEmpty().withMessage('username or email is required'),
35 check('password').notEmpty().withMessage('password is required')
36 ]
37}
38
39// how to use express validator in controller for results message
40const errors = resultsValidator(req)
41 if (errors.length > 0) {
42 return res.status(400).json({
43 method: req.method,
44 status: res.statusCode,
45 error: errors
46 })
47 }
48
49// how to use express validator in route
50route.post('/login', loginValidator(), (req, res) => {
51 return res.status(200).send('Login Sucessfuly');
52});
53
54route.post('/register', registerValidator(), (req, res) => {
55 return res.status(200).send('Register Sucessfuly');
56});
1import { Request } from 'express'
2import { check, validationResult, ValidationError, ValidationChain, Result } from 'express-validator'
3
4export const expressValidator = (req: Request): ValidationError[] => {
5 const errors: Result<ValidationError> = validationResult(req)
6
7 const messages: ValidationError[] = []
8 if (!errors.isEmpty()) {
9 for (const i of errors.array()) {
10 messages.push(i)
11 }
12 }
13 return messages
14}
15
16export const registerValidator = (): ValidationChain[] => [
17 check('email').isEmpty().withMessage('email is required'),
18 check('email').isEmail().withMessage('email is not valid'),
19 check('password').isEmpty().withMessage('password is required'),
20 check('password').isLength({ min: 8 }).withMessage('password must be at least 8 characters')
21]
22
23export const loginValidator = (): ValidationChain[] => [
24 check('email').notEmpty().withMessage('email is required'),
25 check('email').isEmail().withMessage('email is not valid'),
26 check('password').notEmpty().withMessage('pasword is required')
27]
28
29export const emailValidator = (): ValidationChain[] => [
30 check('email').notEmpty().withMessage('email is required'),
31 check('email').isEmail().withMessage('email is not valid')
32]
33
34export const tokenValidator = (): ValidationChain[] => [
35 check('id').notEmpty().withMessage('token is required'),
36 check('id').isBase64().withMessage('token is not valid')
37]
38