Node Express.js Request Validation Scheme with Yup
π project-name
βββπ app
β βββπ Middleware
β β βββ ReqValidate.ts
β βββπ Validators
β βββ RegisterSchema.ts
βββπ routes
β βββ api.routes.ts
βββπ server.ts
βββπ package.json
// app/Middleware/ReqValidate.ts
import { RequestHandler } from "express";
import { ObjectSchema } from "yup";
/**
* `Req Validation Middleware`
* @param schema
* @returns RequestHandler
*/
const ReqValidateBody: ReqValidate = (schema) => async (req, res, next) => {
if (schema.fields && !Object.keys(schema.fields).length) {
return res.status(500).json({status: 422, errors: "Validator schema empty!"});
}
try {
await schema.validate(req.body);
return next();
} catch (errors) {
return res.status(422).json({status: 422, errors});
}
};
type ReqValidate = (schema: ObjectSchema<{}) => RequestHandler;
const ReqValidate = {
body: ReqValidateBody,
};
export default ReqValidate;
// app/Validators/RegisterSchema.ts
import * as schema from "yup";
export const SubscribeSchema = schema.object({
name: schema.string().required(),
username: schema.string().required(),
email: schema.string().required(),
password: schema.string().required(),
confirm_password: schema.string().oneOf([schema.ref('password'), '']).required()
});
// routes/api.routes.ts
import { Router } from "express";
import ReqValidate from "../app/Middleware/ReqValidate";
import { RegisterSchema } from "../app/Validators/RegisterSchema";
const router = Router();
router.post("/register", ReqValidate.body(RegisterSchema), UserController.store);