{"id":18908950,"url":"https://github.com/luckcoding/koa-middle-validator","last_synced_at":"2025-07-13T00:40:30.689Z","repository":{"id":18791758,"uuid":"161612785","full_name":"luckcoding/koa-middle-validator","owner":"luckcoding","description":"Koa middleware for the validator module. Support v1 and v2.","archived":false,"fork":false,"pushed_at":"2022-12-06T18:25:39.000Z","size":69,"stargazers_count":5,"open_issues_count":4,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-04-13T16:51:10.459Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/luckcoding.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-12-13T09:10:03.000Z","updated_at":"2021-10-12T03:49:07.000Z","dependencies_parsed_at":"2023-01-11T20:29:50.707Z","dependency_job_id":null,"html_url":"https://github.com/luckcoding/koa-middle-validator","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luckcoding%2Fkoa-middle-validator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luckcoding%2Fkoa-middle-validator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luckcoding%2Fkoa-middle-validator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luckcoding%2Fkoa-middle-validator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/luckcoding","download_url":"https://codeload.github.com/luckcoding/koa-middle-validator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248757634,"owners_count":21156952,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-08T09:29:48.049Z","updated_at":"2025-04-15T05:32:15.347Z","avatar_url":"https://github.com/luckcoding.png","language":"JavaScript","readme":"# koa-middle-validator\n\n[![npm version](https://img.shields.io/npm/v/koa-middle-validator.svg)](https://www.npmjs.com/package/koa-middle-validator)\n\nKoa middleware for the validator module. Support v1 and v2.\n\n\n## Installation\n\n```\nnpm install koa-middle-validator\n```\n\n## Usage\n\n```javascript\nconst util = require('util'),\nconst Koa = require('koa');\nconst bodyParser = require('koa-bodyparser');\nconst convert = require('koa-convert');\nconst koaValidator = require('koa-middle-validator');\nconst Router = require('koa-router');\nconst _ = require('lodash');\n\nconst app = new Koa();\nconst router = new Router();\n\napp.use(convert(bodyParser()));\napp.use(koaValidator({\n  customValidators: {\n    isArray: function(value) {\n      return _.isArray(value);\n    },\n    isAsyncTest: function(testparam) {\n      return new Promise(function(resolve, reject) {\n        setTimeout(function() {\n          if (testparam === '42') { return resolve(); }\n          reject();\n        }, 200);\n      });\n    }\n  },\n  customSanitizers: {\n    toTestSanitize: function() {\n      return \"!!!!\";\n    }\n  }\n})); // this line must be immediately after any of the bodyParser middlewares!\n\nrouter.get(/\\/test(\\d+)/, validation);\nrouter.get('/:testparam?', validation);\nrouter.post('/:testparam?', validation);\napp.use(router.routes())\napp.use(router.allowedMethods({\n  throw: true\n}))\n\nfunction validation (ctx) {\n  ctx.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();\n  //ctx.checkParams('urlparam', 'Invalid urlparam').isAlpha();\n  ctx.checkQuery('getparam', 'Invalid getparam').isInt();\n\n\n  ctx.sanitizeBody('postparam').toBoolean();\n  //ctx.sanitizeParams('urlparam').toBoolean();\n  ctx.sanitizeQuery('getparam').toBoolean();\n\n  ctx.sanitize('postparam').toBoolean();\n\n  return ctx.getValidationResult().then(function(result) {\n    ctx.body = {\n      //\n    }\n  });\n}\n\napp.listen(8888);\n```\n\n## Middleware Options\n\n#### `errorFormatter`\n\n_function(param,msg,value)_\n\n\n#### `customValidators`\n\n_{ \"validatorName\": function(value, [additional arguments]), ... }_\n\n\n#### `customSanitizers`\n\n_{ \"sanitizerName\": function(value, [additional arguments]), ... }_\n\n\n## Validation\n\n#### ctx.check();\n```javascript\n   ctx.check('testparam', 'Error Message').notEmpty().isInt();\n   ctx.check('testparam.child', 'Error Message').isInt(); // find nested params\n   ctx.check(['testparam', 'child'], 'Error Message').isInt(); // find nested params\n```\n\n#### ctx.assert();\nAlias for [ctx.check()](#reqcheck).\n\n#### ctx.validate();\nAlias for [ctx.check()](#reqcheck).\n\n#### ctx.checkBody();\nSame as [ctx.check()](#reqcheck), but only looks in `ctx.body`.\n\n#### ctx.checkQuery();\nSame as [ctx.check()](#reqcheck), but only looks in `ctx.query`.\n\n#### ctx.checkParams();\nSame as [ctx.check()](#reqcheck), but only looks in `ctx.params`.\n\n#### ctx.checkHeaders();\nOnly checks `ctx.headers`. This method is not covered by the general `ctx.check()`.\n\n#### ~~ctx.checkCookies();~~\n~~Only checks `ctx.cookies`. This method is not covered by the general `ctx.check()`.~~\n\n## Validation by Schema\n\n```javascript\nctx.checkBody({\n 'email': {\n    optional: {\n      options: { checkFalsy: true } // or: [{ checkFalsy: true }]\n    },\n    isEmail: {\n      errorMessage: 'Invalid Email'\n    }\n  },\n  'password': {\n    notEmpty: true,\n    matches: {\n      options: ['example', 'i'] // pass options to the validator with the options property as an array\n      // options: [/example/i] // matches also accepts the full expression in the first parameter\n    },\n    errorMessage: 'Invalid Password' // Error message for the parameter\n  },\n  'name.first': { //\n    optional: true, // won't validate if field is empty\n    isLength: {\n      options: [{ min: 2, max: 10 }],\n      errorMessage: 'Must be between 2 and 10 chars long' // Error message for the validator, takes precedent over parameter message\n    },\n    errorMessage: 'Invalid First Name'\n  }\n});\n```\n\nYou can also define a specific location to validate against in the schema by adding `in` parameter as shown below:\n\n```javascript\nctx.check({\n 'email': {\n    in: 'query',\n    notEmpty: true,\n    isEmail: {\n      errorMessage: 'Invalid Email'\n    }\n  }\n});\n```\n\nctx.check(schema);        // will check 'password' no matter where it is but 'email' in query params\n\nctx.checkQuery(schema);   // will check 'password' and 'email' in query params\n\nctx.checkBody(schema);    // will check 'password' in body but 'email' in query params\n\nctx.checkParams(schema);\n\nctx.checkHeaders(schema);  // will check 'password' in headers but 'email' in query params\n\n\n## Validation result\n\n### getValidationResult\n\nRuns all validations and returns a validation result object for the errors gathered, for both sync and async validators.\n\n```js\nctx.assert('email', 'required').notEmpty();\nctx.assert('email', 'valid email required').isEmail();\nctx.assert('password', '6 to 20 characters required').len(6, 20);\n\nctx.getValidationResult().then(function(result) {\n  // do something with the validation result\n  if (!errors.isEmpty()) {\n    ctx.body = errors.array();\n  } else {\n    // ctx.body = {};\n  }\n});\n```\n\n### getValidationLegalResult (v1.1.0)\n\nRuns all validations and return the validated values;\n\n```js\n  try {\n    ctx.checkBody({})\n\n    const values = await ctx.getValidationLegalResult()\n\n    mongoose.model.save(values)\n  } catch (e) {\n    // $$emit error\n  }\n```\n\n## Optional input\n\n```javascript\nctx.checkBody('email').optional().isEmail();\n//if there is no error, ctx.request.body.email is either undefined or a valid mail.\n```\n\n## Sanitizer\n\n#### ctx.sanitize();\n```javascript\n\nctx.request.body.comment = 'a \u003cspan\u003ecomment\u003c/span\u003e';\nctx.request.body.username = '   a user    ';\n\nctx.sanitize('comment').escape(); // returns 'a \u0026lt;span\u0026gt;comment\u0026lt;/span\u0026gt;'\nctx.sanitize('username').trim(); // returns 'a user'\n\nconsole.log(ctx.request.body.comment); // 'a \u0026lt;span\u0026gt;comment\u0026lt;/span\u0026gt;'\nconsole.log(ctx.request.body.username); // 'a user'\n\n```\n\n#### ctx.filter();\nAlias for [ctx.sanitize()](#reqsanitize).\n\n#### ctx.sanitizeBody();\nSame as [ctx.sanitize()](#reqsanitize), but only looks in `ctx.request.body`.\n\n#### ctx.sanitizeQuery();\nSame as [ctx.sanitize()](#reqsanitize), but only looks in `ctx.request.query`.\n\n#### ctx.sanitizeParams();\nSame as [ctx.sanitize()](#reqsanitize), but only looks in `ctx.params`.\n\n#### ctx.sanitizeHeaders();\nOnly sanitizes `ctx.headers`. This method is not covered by the general `ctx.sanitize()`.\n\n#### ~~ctx.sanitizeCookies();~~\n~~Only sanitizes `ctx.cookies`. This method is not covered by the general `ctx.sanitize()`.~~\n\n## Sanitizer result\n\n### getSanitizerLegalResult (v1.1.0)\n\nRuns all sanitizer and return the sanitized values;\n\n```js\n  try {\n    ctx.sanitizeQuery('page').toInt()\n\n    const values = await ctx.getSanitizerLegalResult()\n\n    mongoose.model.save(values)\n  } catch (e) {\n    // $$emit error\n  }\n```","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluckcoding%2Fkoa-middle-validator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fluckcoding%2Fkoa-middle-validator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluckcoding%2Fkoa-middle-validator/lists"}