Koa 1.x Request Validation Middleware

raw JSON →
1.0.7 verified Thu Apr 23 auth: no javascript abandoned

koa-validate is a middleware designed for Koa 1.x applications to validate incoming request parameters, including body, query, URL parameters, files, and headers. It extends the Koa context with methods like `checkBody`, `checkQuery`, `checkParams`, `checkFile`, and `checkHeader`, allowing developers to define validation rules directly within route handlers. The library internally leverages the `validator.js` library for a wide range of validation methods and also supports custom error messages and data sanitization. It features specialized validation for multipart file uploads (requiring `koa-body`) and advanced JSON body validation using JSONPath expressions. The current stable version is 1.0.7, but it appears to be largely unmaintained, with no significant updates in several years. Its core functionality is built around Koa 1.x's generator-based middleware pattern, making it incompatible with modern Koa 2.x+ `async/await` applications without substantial refactoring or a legacy Koa setup.

error SyntaxError: Unexpected token *
cause Attempting to run Koa 1.x generator function syntax (e.g., `function * ()`) in a Node.js environment without Babel transpilation or if using Koa 2.x+ which expects `async/await`.
fix
Either use a Node.js version that natively supports generators (older), configure Babel to transpile generators, or, more likely, recognize that this library is for Koa 1.x and switch to a modern Koa validation library compatible with async/await.
error TypeError: app.use is not a function
cause This error can occur if you're trying to use `koa-validate` with Koa 2.x+ and have used `import Koa from 'koa'` instead of `const Koa = require('koa')` for Koa 1.x. The Koa 1.x application instance is different.
fix
If using Koa 1.x, ensure var koa = require('koa'); var app = koa();. If using Koa 2.x+, koa-validate is not compatible, use an alternative library.
error TypeError: this.checkBody is not a function
cause The `require('koa-validate')(app);` initialization line, which extends the Koa application context, was omitted or placed incorrectly (e.g., after the routes are defined).
fix
Ensure require('koa-validate')(app); is called early in your application setup, typically after the Koa app instance is created but before routes are defined and middleware are processed.
error Error: Missing multipart body or file field for validation
cause When using `this.checkFile()`, the `koa-body` middleware is either not installed, not configured for `multipart: true`, or not applied before the route handler.
fix
Install koa-body (npm install koa-body --save) and ensure app.use(require('koa-body')({multipart:true, formidable:{keepExtensions:true}})); is correctly placed before your routes and checkFile calls.
breaking This library is built for Koa 1.x applications which use generator functions (`function *`). It is fundamentally incompatible with Koa 2.x and later, which adopted `async/await` syntax for middleware. Direct use with modern Koa will lead to `SyntaxError` or unexpected behavior.
fix For Koa 2.x+, consider using `koa-json-schema`, `koa-joi-router`, or `koa-better-validate` as alternatives. Migrating to Koa 2.x would require a complete rewrite of validation logic.
deprecated The package appears to be unmaintained. The latest release (1.0.7) was published several years ago, and there has been no significant activity since, making it a potential security risk or source of incompatibility with newer Node.js versions or dependencies.
fix Evaluate migration to a more actively maintained validation library for Koa 2.x+. If stuck on Koa 1.x, proceed with caution and consider auditing the codebase for vulnerabilities.
gotcha `checkFile` functionality relies on `koa-body` middleware for parsing multipart form data and handling file uploads. If `koa-body` is not installed and configured correctly before `koa-validate` is initialized, `checkFile` will not work as expected.
fix Ensure `npm install koa-body --save` and `app.use(require('koa-body')({multipart:true, formidable:{keepExtensions:true}}));` are correctly placed before router and validation middleware.
gotcha Error handling in `koa-validate` relies on checking `this.errors` directly within the generator function. Modern Koa practices often involve throwing HTTP errors (`ctx.throw`) or using centralized error handling middleware, which is not directly compatible with this pattern.
fix If migrating to Koa 2.x, adapt error handling to use `ctx.throw` or a custom error middleware. If remaining on Koa 1.x, continue to check `this.errors` explicitly after validation calls.
npm install koa-validate
yarn add koa-validate
pnpm add koa-validate

This quickstart demonstrates basic request body and file validation using `koa-validate` within a Koa 1.x application, showing error handling and data sanitization for signup.

'use strict';
var koa = require('koa');
var app = koa();
var router = require('koa-router')();
require('koa-validate')(app);

app.use(require('koa-body')({multipart:true , formidable:{keepExtensions:true}}));
app.use(router.routes()).use(router.allowedMethods());

router.post('/signup', function * () {
	// Validate request body parameters
	this.checkBody('name').optional().len(2, 20, "Name must be between 2 and 20 characters.");
	this.checkBody('email').isEmail("Invalid email address provided.");
	this.checkBody('password').notEmpty().len(3, 20).md5();
	
	// Sanitize and get value
	var age = this.checkBody('age').toInt().value;
	
	// Example file validation (requires koa-body)
	yield this.checkFile('icon').notEmpty().size(0, 300 * 1024, 'File too large (max 300KB)');
	
	// Check for accumulated errors
	if (this.errors) {
		this.status = 400;
		this.body = this.errors;
		return;
	}
	
	this.body = { message: 'Signup successful!', age: age };
});

app.listen(3000, () => console.log('Koa 1.x app listening on port 3000'));