express validator typescript code example

Example 1: express validator

// 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-9\s]/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');
});

Example 2: express validator

npm install --save express-validator

Example 3: express validator typescript

import { Request } from 'express'
import { check, validationResult, ValidationError, ValidationChain, Result } from 'express-validator'

export const expressValidator = (req: Request): ValidationError[] => {
	const errors: Result<ValidationError> = validationResult(req)

	const messages: ValidationError[] = []
	if (!errors.isEmpty()) {
		for (const i of errors.array()) {
			messages.push(i)
		}
	}
	return messages
}

export const registerValidator = (): ValidationChain[] => [
	check('email').isEmpty().withMessage('email is required'),
	check('email').isEmail().withMessage('email is not valid'),
	check('password').isEmpty().withMessage('password is required'),
	check('password').isLength({ min: 8 }).withMessage('password must be at least 8 characters')
]

export const loginValidator = (): ValidationChain[] => [
	check('email').notEmpty().withMessage('email is required'),
	check('email').isEmail().withMessage('email is not valid'),
	check('password').notEmpty().withMessage('pasword is required')
]

export const emailValidator = (): ValidationChain[] => [
	check('email').notEmpty().withMessage('email is required'),
	check('email').isEmail().withMessage('email is not valid')
]

export const tokenValidator = (): ValidationChain[] => [
	check('id').notEmpty().withMessage('token is required'),
	check('id').isBase64().withMessage('token is not valid')
]