Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 97revenge/669d2f301c2c1c4ddb18bda27fe45ba7 to your computer and use it in GitHub Desktop.
Save 97revenge/669d2f301c2c1c4ddb18bda27fe45ba7 to your computer and use it in GitHub Desktop.
Node Express.js Request Validation Scheme with Yup

Node Express.js Request Validation Scheme with Yup

Example Folder Structure

πŸ“ project-name
 β”œβ”€β”€πŸ“ app
 β”‚   β”œβ”€β”€πŸ“ Middleware    
 β”‚   β”‚   └── ReqValidate.ts
 β”‚   β””β”€β”€πŸ“ Validators    
 β”‚       └── RegisterSchema.ts
 β”œβ”€β”€πŸ“ routes
 β”‚   └── api.routes.ts
 β”œβ”€β”€πŸ“„ server.ts    
 β”œβ”€β”€πŸ“„ package.json   

- Middleware

// 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;

- Validator Schema

// 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()
});

- Router

// 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment