Koa 1.x Request Validation Middleware
raw JSON →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.
Common errors
error SyntaxError: Unexpected token * ↓
async/await. error TypeError: app.use is not a function ↓
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 ↓
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 ↓
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. Warnings
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. ↓
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. ↓
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. ↓
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. ↓
Install
npm install koa-validate yarn add koa-validate pnpm add koa-validate Imports
- Initializer wrong
import KoaValidate from 'koa-validate'; // Incorrect for CJS const KoaValidate = require('koa-validate'); // Incorrect for direct use, it's an initializercorrectrequire('koa-validate')(app); - checkBody (on context) wrong
ctx.checkBody('fieldName'); // Incorrect for Koa 1.x, which uses 'this' checkBody('fieldName'); // Not a global functioncorrectthis.checkBody('fieldName').len(2, 20); - this.errors (on context) wrong
if (ctx.errors) { /* handle errors */ } // Incorrect for Koa 1.xcorrectif (this.errors) { /* handle errors */ }
Quickstart
'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'));