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, Meta } 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('firstName').notEmpty().withMessage('firstName is required'),
18 check('firstName')
19 .not()
20 .custom((val: string) => /[^a-zA-Z]/gi.test(val))
21 .withMessage('firstName cannot include unique character'),
22 check('lastName').notEmpty().withMessage('lastName is required'),
23 check('lastName')
24 .not()
25 .custom((val: string) => /[^a-zA-Z]/gi.test(val))
26 .withMessage('lastName cannot include unique character'),
27 check('email').notEmpty().withMessage('email is required'),
28 check('email').isEmail().withMessage('email is not valid'),
29 check('password').notEmpty().withMessage('password is required'),
30 check('password').isLength({ min: 8 }).withMessage('password must be at least 8 characters'),
31 check('location').notEmpty().withMessage('location is required'),
32 check('location')
33 .not()
34 .custom((val: string) => /[^a-zA-Z]/gi.test(val))
35 .withMessage('location cannot include unique character'),
36 check('phone').notEmpty().withMessage('phone is required'),
37 check('phone').isLength({ min: 10 }).withMessage('phone number must be at least 10 characters'),
38 check('phone').isLength({ max: 12 }).withMessage('phone number must be at least 12 characters'),
39 check('phone').isMobilePhone('id-ID').withMessage('phone number is not valid')
40]
41
42export const loginValidator = (): ValidationChain[] => [
43 check('email').notEmpty().withMessage('email is required'),
44 check('email').isEmail().withMessage('email is not valid'),
45 check('password').notEmpty().withMessage('pasword is required')
46]
47
48export const emailValidator = (): ValidationChain[] => [
49 check('email').notEmpty().withMessage('email is required'),
50 check('email').isEmail().withMessage('email is not valid')
51]
52
53export const tokenValidator = (): ValidationChain[] => [
54 check('token').notEmpty().withMessage('token is required'),
55 check('token').isBase64().withMessage('token is not valid')
56]
57
58export const passwordValidator = (): ValidationChain[] => [
59 check('password').notEmpty().withMessage('password is required'),
60 check('password').isLength({ min: 8 }).withMessage('password must be at least 8 characters'),
61 check('password')
62 .not()
63 .custom((value: string, { req }: Meta) => req.body.cpassword !== value)
64 .withMessage('confirm password is not match with password'),
65 check('cpassword').notEmpty().withMessage('cpassword is required'),
66 check('cpassword').isLength({ min: 8 }).withMessage('cpassword must be at least 8 characters')
67]
1app.post('/form', [
2 check('name').isLength({ min: 3 }),
3 check('email').isEmail(),
4 check('age').isNumeric()
5], (req, res) => {
6 const errors = validationResult(req)
7 if (!errors.isEmpty()) {
8 return res.status(422).json({ errors: errors.array() })
9 }
10
11 const name = req.body.name
12 const email = req.body.email
13 const age = req.body.age
14})
15
1const { check } = require('express-validator');
2
3app.post(
4 '/user',
5 // ...some other validations...
6 check('password')
7 .isLength({ min: 5 })
8 .withMessage('must be at least 5 chars long')
9 .matches(/\d/)
10 .withMessage('must contain a number'),
11 (req, res) => {
12 // Handle the request somehow
13 },
14);
15
1// ...rest of the initial code omitted for simplicity.
2const { body, validationResult } = require('express-validator');
3
4app.post('/user', [
5 // username must be an email
6 body('username').isEmail(),
7 // password must be at least 5 chars long
8 body('password').isLength({ min: 5 })
9], (req, res) => {
10 // Finds the validation errors in this request and wraps them in an object with handy functions
11 const errors = validationResult(req);
12 if (!errors.isEmpty()) {
13 return res.status(422).json({ errors: errors.array() });
14 }
15
16 User.create({
17 username: req.body.username,
18 password: req.body.password
19 }).then(user => res.json(user));
20});
21