Mon Apr 15 2024

Data Validation using Middleware and JOI

Node JS41 views
Data Validation using Middleware and JOI

File Name: validateResource.js

const validateResource = (schema) => async (req, res, next) => {
  const options = {
    abortEarly: false,
    allowUnknown: true,
    stripUnknown: true,
  };

  try {
    await schema.validateAsync(
      {
        body: req.body,
        query: req.query,
        params: req.params,
      },
      options
    );
    next();
  } catch (e) {
    return res.status(400).jsonp(e.details);
  }
};

module.exports = validateResource;

File Name: user.schema.js

const Joi = require("joi");

const createUserSchema = Joi.object({
  body: Joi.object({
    fullName: Joi.string().required(),
    email: Joi.string().email().required(),
    password: Joi.string().required(),
    confirmPassword: Joi.string().valid(Joi.ref("password")).required(),
  }),
});

const loginUserSchema = Joi.object({
  body: Joi.object({
    email: Joi.string().email().required(),
    password: Joi.string().required(),
  }),
});

module.exports = { createUserSchema, loginUserSchema };

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.