diff --git a/README.md b/README.md index 9ff8e95..7d5a49b 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,19 @@ NodeJS validation middleware for express router using schemas for both body and This library allows you to use any validation library, even your own. Examples are using [validator](https://github.com/validatorjs/validator.js) -# Installation and usage +# Table of contents +1. [Installation](#installation) +2. [Quick example](#quick-example) +3. [Schema structure](#schema-structure) +4. [Optional fields](#optional-fields) +5. [Validating both body and parameters](#validating-both-body-and-parameters) +6. [Validation output](#validation-output) +7. [Using field values in messages](#using-field-values-in-messages) +8. [Async/await validation](#asyncawait-validation) +9. [Cross field validation](#cross-field-validation) +10. [Contributing](#contributing) + +## Installation > npm i nodejs-schema-validator ## Quick example @@ -40,6 +52,7 @@ router.post( ); ``` +## Schema structure Here's a breakdown of how the schema is structured: ```js @@ -69,6 +82,22 @@ const schemaExample = { } } ``` + +## Optional fields +Marking fields as optional will validate only when they are not empty. +```js +const schema = { + vatNo: { + // Some fields can be optional + optional: true, + rules: [ + rule: (input) => !validator.isValidVatNo(input), + message: 'Please insert a valid VAT number of leave empty' + ] + } +} +``` + ## Validating both body and parameters Example of how to validate both body and url parameters @@ -104,7 +133,7 @@ router.put( ) ``` - +## Validation output Validation failure returns status code 422 with a body in this format: ```js { @@ -117,7 +146,6 @@ Validation failure returns status code 422 with a body in this format: } ``` -## Custom validation output In case you want to customize the output and status code of the failure you can pass a function as the second parameter to the middleware. It can be passed to both `paramSchemaValidator` and `bodySchemaValidator`. ```js @@ -133,6 +161,7 @@ router.post( ``` ## Using field values in messages +Field names wrapped in double curly braces will be replaced with their values. **Please note that there should be no space between the field name and the braces**. ```js const schema = { amount: { @@ -146,7 +175,7 @@ const schema = { }; ``` -## Validating with async/await +## Async/await validation Schema rules support async methods. Here's an example: ```js @@ -154,7 +183,7 @@ const schema = { email: { rules: [ { - rule: async (input) => await emailExists(), + rule: async (input) => await emailExists(input), message: 'Email address {{email}} already exists' } ] diff --git a/package.json b/package.json index 777a2ba..c4c04c8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nodejs-schema-validator", - "version": "0.10.2", + "version": "0.10.3", "description": "NodeJS validation using schemas", "main": "./src/schema-validator.js", "scripts": {