Simple, opinionated request validation middleware for koa-router.
This module currently supports Koa 1 only.
const Joi = ;const router = ;const validate = ;router;
Why is the result assigned to
request wrapper object automatically serializes all values assigned to its
query property. This means that its values can not actually be coerced to other types, e.g. to numbers or booleans. To resolve this the modified data (conversions and defaults applied) are assigned to
Install as usual:
npm install --save koa-joiful-validation
Please note that this module has Joi as a peer dependency (practically any version will do).
In order for the request body validation to work correctly you will want to use koa-bodyparser.
This module is quite opinionated. If it doesn't suit your needs, feel free to open an issue, create a pull request or just fork the project. In particular, keep the following things in mind:
- If a validation fails, so does the request with a
422 Unprocessable Entityerror.
- All parameters are required by default (
- Additional parameters, i.e. parameters not specified in the schemas, are forbidden by default.
- When no schema is given, the empty schema is assumed. This means that
router.post('/', validate(), ...)will not accept any query, body or url parameters.
- By default, query and url parameters are converted (e.g., cast to numbers as necessary), but body parameters are not.
If you have route parameters, you need to add them to your validation config in order to work:
So instead, do it like this:
If you do not want to actually validate the parameter, simply use
Custom validation functions
You can pass a list of custom validation functions as a second parameter:
These functions are run in sequence after the schema validations (and only if those succeed). If a function returns a string, that validation is considered to have failed and the string becomes the error message. Any other return value is interpreted as a success.
The functions are executed in the same context as the middleware itself so you have access to
If your validation is asynchronous, simply use a generator:
Please note that throwing an error from a validation function will abort the request with a
500 Internal Server Error.
The values given in the configuration object are automatically passed to
Joi.object().keys() if they are not already Joi schemas. In other words, the following two statements are equivalent: