Options
All
  • Public
  • Public/Protected
  • All
Menu

koa-req-validation

koa-req-validation

Node.js CI npm package Libraries.io dependency status for latest release codecov Known Vulnerabilities

A validator middleware for koa. Inspired by express-validator.

Installation

The koa-req-validation requires validator, @koa/router and koa-bodyparser as peer dependencies.

Install peer dependencies

npm install validator@13 koa-bodyparser@4 @koa/router@10

Install koa-req-validation

npm install koa-req-validation

Getting started

A basic usage example

import Router, { RouterContext } from "@koa/router";
import { query, validationResults } from "koa-req-validation";

// ...

const router = new Router();

router.get(
"/api/hello",
query("name")
.isLength({ min: 3, max: 20 })
.withMessage("The name has to be between 3 and 20 characters")
.build(), // <-- This is required at the end of each validation
async (ctx: RouterContext) => {
const result = validationResults(ctx);
if (result.hasErrors()) {
throw new RequestError(422, result.mapped());
}
const { name } = ctx.query;
ctx.body = `Hello ${name}`;
}
);

See the demo for other examples.

Documentation

This module offers various validation and sanitation functions. Please note the following things:

  • Nested objects can now be validated
    • Support has been added to the ValidationResult.passedData() output as well
  • The order matters
    • The validations and sanitations are being run in order they've been called in the validation chain
  • No sanitations are run for a chain after some of the validations has failed
    • This is due to the fact that some of the sanitizers rely on "valid" value (for example valid email address)
  • The sanitized values can be accessed only through ValidationResult.passedData()
    • The request body is treated as immutable in the validation middleware
const result = validationResults(ctx);
if (result.hasErrors()) {
throw new RequestError(422, result.mapped());
}
const passed = result.passedData();

See the generated TypeDoc and ValidationChain for API documentation.

Issues

We use GitHub for issue tracking. Please look from previously submitted issues if someone else has already submitted the same issue.

Changelog

Please see releases.

Contribution

All contributions to the project are welcome.

Licence

ISC Licence

Generated using TypeDoc