Mon Apr 15 2024
Data Validation using Middleware and JOI
Node JS42 views
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 };
Author:Geekboots