{"id":17764,"library":"koa-validate","title":"Koa 1.x Request Validation Middleware","description":"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.","status":"abandoned","version":"1.0.7","language":"javascript","source_language":"en","source_url":"https://github.com/RocksonZeta/koa-validate","tags":["javascript","web","koa","koa-validate","validate","validator","format","middleware"],"install":[{"cmd":"npm install koa-validate","lang":"bash","label":"npm"},{"cmd":"yarn add koa-validate","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-validate","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core Koa 1.x application framework dependency.","package":"koa","optional":false},{"reason":"Used in examples for routing, but not a direct dependency of koa-validate itself.","package":"koa-router","optional":true},{"reason":"Required for `checkFile` functionality and body parsing, especially multipart forms.","package":"koa-body","optional":true},{"reason":"Underlying library providing validation functions.","package":"validator","optional":false}],"imports":[{"note":"The package exports an initializer function that must be called with your Koa application instance to extend its context. It's a CommonJS module.","wrong":"import KoaValidate from 'koa-validate'; // Incorrect for CJS\nconst KoaValidate = require('koa-validate'); // Incorrect for direct use, it's an initializer","symbol":"Initializer","correct":"require('koa-validate')(app);"},{"note":"After initialization, validation methods like `checkBody` are available on the `this` context within Koa 1.x generator middleware functions.","wrong":"ctx.checkBody('fieldName'); // Incorrect for Koa 1.x, which uses 'this'\ncheckBody('fieldName'); // Not a global function","symbol":"checkBody (on context)","correct":"this.checkBody('fieldName').len(2, 20);"},{"note":"Validation errors are accumulated in `this.errors` on the Koa 1.x context after validation methods are called.","wrong":"if (ctx.errors) { /* handle errors */ } // Incorrect for Koa 1.x","symbol":"this.errors (on context)","correct":"if (this.errors) { /* handle errors */ }"}],"quickstart":{"code":"'use strict';\nvar koa = require('koa');\nvar app = koa();\nvar router = require('koa-router')();\nrequire('koa-validate')(app);\n\napp.use(require('koa-body')({multipart:true , formidable:{keepExtensions:true}}));\napp.use(router.routes()).use(router.allowedMethods());\n\nrouter.post('/signup', function * () {\n\t// Validate request body parameters\n\tthis.checkBody('name').optional().len(2, 20, \"Name must be between 2 and 20 characters.\");\n\tthis.checkBody('email').isEmail(\"Invalid email address provided.\");\n\tthis.checkBody('password').notEmpty().len(3, 20).md5();\n\t\n\t// Sanitize and get value\n\tvar age = this.checkBody('age').toInt().value;\n\t\n\t// Example file validation (requires koa-body)\n\tyield this.checkFile('icon').notEmpty().size(0, 300 * 1024, 'File too large (max 300KB)');\n\t\n\t// Check for accumulated errors\n\tif (this.errors) {\n\t\tthis.status = 400;\n\t\tthis.body = this.errors;\n\t\treturn;\n\t}\n\t\n\tthis.body = { message: 'Signup successful!', age: age };\n});\n\napp.listen(3000, () => console.log('Koa 1.x app listening on port 3000'));","lang":"javascript","description":"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."},"warnings":[{"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.","message":"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.","severity":"breaking","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"deprecated","affected_versions":">=1.0.0"},{"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.","message":"`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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"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`.","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`.","error":"SyntaxError: Unexpected token *"},{"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.","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.","error":"TypeError: app.use is not a function"},{"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.","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).","error":"TypeError: this.checkBody is not a function"},{"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.","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.","error":"Error: Missing multipart body or file field for validation"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}