From 1c0c03ae020503f5c38238b7b49e740ce6dd020d Mon Sep 17 00:00:00 2001 From: Gustavo Henke Date: Wed, 26 Apr 2023 17:57:01 +1000 Subject: [PATCH] Deploy website - based on a49a454bd4cedb2c3af623f956c1ad09c57d391d --- 404.html | 4 ++-- assets/js/{4e289b8c.c33a8e6e.js => 4e289b8c.b2f5880a.js} | 2 +- assets/js/{609507dd.fc0c4e35.js => 609507dd.f2a4e177.js} | 2 +- assets/js/60e2c3e9.e99e4a3b.js | 1 + assets/js/60e2c3e9.eaaa856f.js | 1 - assets/js/84854274.24286938.js | 1 - assets/js/84854274.82275863.js | 1 + .../{runtime~main.c46e207b.js => runtime~main.96406a10.js} | 2 +- docs/5.2.0/check-api/index.html | 4 ++-- docs/5.2.0/custom-error-messages/index.html | 4 ++-- docs/5.2.0/custom-validators-sanitizers/index.html | 4 ++-- docs/5.2.0/filter-api/index.html | 4 ++-- docs/5.2.0/index.html | 4 ++-- docs/5.2.0/legacy-api/index.html | 4 ++-- docs/5.2.0/sanitization-chain-api/index.html | 4 ++-- docs/5.2.0/sanitization/index.html | 4 ++-- docs/5.2.0/schema-validation/index.html | 4 ++-- docs/5.2.0/validation-chain-api/index.html | 4 ++-- docs/5.2.0/validation-result-api/index.html | 4 ++-- docs/5.2.0/whole-body-validation/index.html | 4 ++-- docs/5.2.0/wildcards/index.html | 4 ++-- docs/5.3.0/check-api/index.html | 4 ++-- docs/5.3.0/custom-error-messages/index.html | 4 ++-- docs/5.3.0/custom-validators-sanitizers/index.html | 4 ++-- docs/5.3.0/filter-api/index.html | 4 ++-- docs/5.3.0/index.html | 4 ++-- docs/5.3.0/legacy-api/index.html | 4 ++-- docs/5.3.0/sanitization-chain-api/index.html | 4 ++-- docs/5.3.0/sanitization/index.html | 4 ++-- docs/5.3.0/schema-validation/index.html | 4 ++-- docs/5.3.0/validation-chain-api/index.html | 4 ++-- docs/5.3.0/validation-result-api/index.html | 4 ++-- docs/5.3.0/whole-body-validation/index.html | 4 ++-- docs/5.3.0/wildcards/index.html | 4 ++-- docs/6.0.0/check-api/index.html | 4 ++-- docs/6.0.0/custom-error-messages/index.html | 4 ++-- docs/6.0.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.0.0/filter-api/index.html | 4 ++-- docs/6.0.0/index.html | 4 ++-- docs/6.0.0/matched-data-api/index.html | 4 ++-- docs/6.0.0/running-imperatively/index.html | 4 ++-- docs/6.0.0/sanitization-chain-api/index.html | 4 ++-- docs/6.0.0/sanitization/index.html | 4 ++-- docs/6.0.0/schema-validation/index.html | 4 ++-- docs/6.0.0/validation-chain-api/index.html | 4 ++-- docs/6.0.0/validation-result-api/index.html | 4 ++-- docs/6.0.0/whole-body-validation/index.html | 4 ++-- docs/6.0.0/wildcards/index.html | 4 ++-- docs/6.1.0/check-api/index.html | 4 ++-- docs/6.1.0/custom-error-messages/index.html | 4 ++-- docs/6.1.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.1.0/filter-api/index.html | 4 ++-- docs/6.1.0/index.html | 4 ++-- docs/6.1.0/matched-data-api/index.html | 4 ++-- docs/6.1.0/running-imperatively/index.html | 4 ++-- docs/6.1.0/sanitization-chain-api/index.html | 4 ++-- docs/6.1.0/sanitization/index.html | 4 ++-- docs/6.1.0/schema-validation/index.html | 4 ++-- docs/6.1.0/validation-chain-api/index.html | 4 ++-- docs/6.1.0/validation-result-api/index.html | 4 ++-- docs/6.1.0/whole-body-validation/index.html | 4 ++-- docs/6.1.0/wildcards/index.html | 4 ++-- docs/6.10.0/check-api/index.html | 4 ++-- docs/6.10.0/custom-error-messages/index.html | 4 ++-- docs/6.10.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.10.0/faq/index.html | 4 ++-- docs/6.10.0/filter-api/index.html | 4 ++-- docs/6.10.0/index.html | 4 ++-- docs/6.10.0/matched-data-api/index.html | 4 ++-- docs/6.10.0/migration-v5-to-v6/index.html | 4 ++-- docs/6.10.0/running-imperatively/index.html | 4 ++-- docs/6.10.0/sanitization-chain-api/index.html | 4 ++-- docs/6.10.0/sanitization/index.html | 4 ++-- docs/6.10.0/schema-validation/index.html | 4 ++-- docs/6.10.0/validation-chain-api/index.html | 4 ++-- docs/6.10.0/validation-result-api/index.html | 4 ++-- docs/6.10.0/whole-body-validation/index.html | 4 ++-- docs/6.10.0/wildcards/index.html | 4 ++-- docs/6.11.0/check-api/index.html | 4 ++-- docs/6.11.0/custom-error-messages/index.html | 4 ++-- docs/6.11.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.11.0/faq/index.html | 4 ++-- docs/6.11.0/filter-api/index.html | 4 ++-- docs/6.11.0/index.html | 4 ++-- docs/6.11.0/matched-data-api/index.html | 4 ++-- docs/6.11.0/migration-v5-to-v6/index.html | 4 ++-- docs/6.11.0/running-imperatively/index.html | 4 ++-- docs/6.11.0/sanitization-chain-api/index.html | 4 ++-- docs/6.11.0/sanitization/index.html | 4 ++-- docs/6.11.0/schema-validation/index.html | 4 ++-- docs/6.11.0/validation-chain-api/index.html | 4 ++-- docs/6.11.0/validation-result-api/index.html | 4 ++-- docs/6.11.0/whole-body-validation/index.html | 4 ++-- docs/6.11.0/wildcards/index.html | 4 ++-- docs/6.12.0/check-api/index.html | 4 ++-- docs/6.12.0/custom-error-messages/index.html | 4 ++-- docs/6.12.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.12.0/faq/index.html | 4 ++-- docs/6.12.0/filter-api/index.html | 4 ++-- docs/6.12.0/index.html | 4 ++-- docs/6.12.0/matched-data-api/index.html | 4 ++-- docs/6.12.0/migration-v5-to-v6/index.html | 4 ++-- docs/6.12.0/running-imperatively/index.html | 4 ++-- docs/6.12.0/sanitization-chain-api/index.html | 4 ++-- docs/6.12.0/sanitization/index.html | 4 ++-- docs/6.12.0/schema-validation/index.html | 4 ++-- docs/6.12.0/validation-chain-api/index.html | 4 ++-- docs/6.12.0/validation-result-api/index.html | 4 ++-- docs/6.12.0/whole-body-validation/index.html | 4 ++-- docs/6.12.0/wildcards/index.html | 4 ++-- docs/6.13.0/check-api/index.html | 4 ++-- docs/6.13.0/custom-error-messages/index.html | 4 ++-- docs/6.13.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.13.0/faq/index.html | 4 ++-- docs/6.13.0/filter-api/index.html | 4 ++-- docs/6.13.0/index.html | 4 ++-- docs/6.13.0/matched-data-api/index.html | 4 ++-- docs/6.13.0/migration-v5-to-v6/index.html | 4 ++-- docs/6.13.0/running-imperatively/index.html | 4 ++-- docs/6.13.0/sanitization-chain-api/index.html | 4 ++-- docs/6.13.0/sanitization/index.html | 4 ++-- docs/6.13.0/schema-validation/index.html | 4 ++-- docs/6.13.0/validation-chain-api/index.html | 4 ++-- docs/6.13.0/validation-result-api/index.html | 4 ++-- docs/6.13.0/whole-body-validation/index.html | 4 ++-- docs/6.13.0/wildcards/index.html | 4 ++-- docs/6.14.0/check-api/index.html | 4 ++-- docs/6.14.0/custom-error-messages/index.html | 4 ++-- docs/6.14.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.14.0/faq/index.html | 4 ++-- docs/6.14.0/filter-api/index.html | 4 ++-- docs/6.14.0/index.html | 4 ++-- docs/6.14.0/matched-data-api/index.html | 4 ++-- docs/6.14.0/migration-v5-to-v6/index.html | 4 ++-- docs/6.14.0/running-imperatively/index.html | 4 ++-- docs/6.14.0/sanitization-chain-api/index.html | 4 ++-- docs/6.14.0/sanitization/index.html | 4 ++-- docs/6.14.0/schema-validation/index.html | 4 ++-- docs/6.14.0/validation-chain-api/index.html | 4 ++-- docs/6.14.0/validation-result-api/index.html | 4 ++-- docs/6.14.0/whole-body-validation/index.html | 4 ++-- docs/6.14.0/wildcards/index.html | 4 ++-- docs/6.15.0/check-api/index.html | 4 ++-- docs/6.15.0/custom-error-messages/index.html | 4 ++-- docs/6.15.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.15.0/faq/index.html | 4 ++-- docs/6.15.0/filter-api/index.html | 4 ++-- docs/6.15.0/index.html | 4 ++-- docs/6.15.0/matched-data-api/index.html | 4 ++-- docs/6.15.0/migration-v5-to-v6/index.html | 4 ++-- docs/6.15.0/running-imperatively/index.html | 4 ++-- docs/6.15.0/sanitization-chain-api/index.html | 4 ++-- docs/6.15.0/sanitization/index.html | 4 ++-- docs/6.15.0/schema-validation/index.html | 4 ++-- docs/6.15.0/validation-chain-api/index.html | 4 ++-- docs/6.15.0/validation-result-api/index.html | 4 ++-- docs/6.15.0/whole-body-validation/index.html | 4 ++-- docs/6.15.0/wildcards/index.html | 4 ++-- docs/6.2.0/check-api/index.html | 4 ++-- docs/6.2.0/custom-error-messages/index.html | 4 ++-- docs/6.2.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.2.0/filter-api/index.html | 4 ++-- docs/6.2.0/index.html | 4 ++-- docs/6.2.0/matched-data-api/index.html | 4 ++-- docs/6.2.0/running-imperatively/index.html | 4 ++-- docs/6.2.0/sanitization-chain-api/index.html | 4 ++-- docs/6.2.0/sanitization/index.html | 4 ++-- docs/6.2.0/schema-validation/index.html | 4 ++-- docs/6.2.0/validation-chain-api/index.html | 4 ++-- docs/6.2.0/validation-result-api/index.html | 4 ++-- docs/6.2.0/whole-body-validation/index.html | 4 ++-- docs/6.2.0/wildcards/index.html | 4 ++-- docs/6.3.0/check-api/index.html | 4 ++-- docs/6.3.0/custom-error-messages/index.html | 4 ++-- docs/6.3.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.3.0/filter-api/index.html | 4 ++-- docs/6.3.0/index.html | 4 ++-- docs/6.3.0/matched-data-api/index.html | 4 ++-- docs/6.3.0/running-imperatively/index.html | 4 ++-- docs/6.3.0/sanitization-chain-api/index.html | 4 ++-- docs/6.3.0/sanitization/index.html | 4 ++-- docs/6.3.0/schema-validation/index.html | 4 ++-- docs/6.3.0/validation-chain-api/index.html | 4 ++-- docs/6.3.0/validation-result-api/index.html | 4 ++-- docs/6.3.0/whole-body-validation/index.html | 4 ++-- docs/6.3.0/wildcards/index.html | 4 ++-- docs/6.4.0/check-api/index.html | 4 ++-- docs/6.4.0/custom-error-messages/index.html | 4 ++-- docs/6.4.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.4.0/filter-api/index.html | 4 ++-- docs/6.4.0/index.html | 4 ++-- docs/6.4.0/matched-data-api/index.html | 4 ++-- docs/6.4.0/running-imperatively/index.html | 4 ++-- docs/6.4.0/sanitization-chain-api/index.html | 4 ++-- docs/6.4.0/sanitization/index.html | 4 ++-- docs/6.4.0/schema-validation/index.html | 4 ++-- docs/6.4.0/validation-chain-api/index.html | 4 ++-- docs/6.4.0/validation-result-api/index.html | 4 ++-- docs/6.4.0/whole-body-validation/index.html | 4 ++-- docs/6.4.0/wildcards/index.html | 4 ++-- docs/6.5.0/check-api/index.html | 4 ++-- docs/6.5.0/custom-error-messages/index.html | 4 ++-- docs/6.5.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.5.0/filter-api/index.html | 4 ++-- docs/6.5.0/index.html | 4 ++-- docs/6.5.0/matched-data-api/index.html | 4 ++-- docs/6.5.0/running-imperatively/index.html | 4 ++-- docs/6.5.0/sanitization-chain-api/index.html | 4 ++-- docs/6.5.0/sanitization/index.html | 4 ++-- docs/6.5.0/schema-validation/index.html | 4 ++-- docs/6.5.0/validation-chain-api/index.html | 4 ++-- docs/6.5.0/validation-result-api/index.html | 4 ++-- docs/6.5.0/whole-body-validation/index.html | 4 ++-- docs/6.5.0/wildcards/index.html | 4 ++-- docs/6.6.0/check-api/index.html | 4 ++-- docs/6.6.0/custom-error-messages/index.html | 4 ++-- docs/6.6.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.6.0/filter-api/index.html | 4 ++-- docs/6.6.0/index.html | 4 ++-- docs/6.6.0/matched-data-api/index.html | 4 ++-- docs/6.6.0/running-imperatively/index.html | 4 ++-- docs/6.6.0/sanitization-chain-api/index.html | 4 ++-- docs/6.6.0/sanitization/index.html | 4 ++-- docs/6.6.0/schema-validation/index.html | 4 ++-- docs/6.6.0/validation-chain-api/index.html | 4 ++-- docs/6.6.0/validation-result-api/index.html | 4 ++-- docs/6.6.0/whole-body-validation/index.html | 4 ++-- docs/6.6.0/wildcards/index.html | 4 ++-- docs/6.7.0/check-api/index.html | 4 ++-- docs/6.7.0/custom-error-messages/index.html | 4 ++-- docs/6.7.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.7.0/filter-api/index.html | 4 ++-- docs/6.7.0/index.html | 4 ++-- docs/6.7.0/matched-data-api/index.html | 4 ++-- docs/6.7.0/running-imperatively/index.html | 4 ++-- docs/6.7.0/sanitization-chain-api/index.html | 4 ++-- docs/6.7.0/sanitization/index.html | 4 ++-- docs/6.7.0/schema-validation/index.html | 4 ++-- docs/6.7.0/validation-chain-api/index.html | 4 ++-- docs/6.7.0/validation-result-api/index.html | 4 ++-- docs/6.7.0/whole-body-validation/index.html | 4 ++-- docs/6.7.0/wildcards/index.html | 4 ++-- docs/6.8.0/check-api/index.html | 4 ++-- docs/6.8.0/custom-error-messages/index.html | 4 ++-- docs/6.8.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.8.0/filter-api/index.html | 4 ++-- docs/6.8.0/index.html | 4 ++-- docs/6.8.0/matched-data-api/index.html | 4 ++-- docs/6.8.0/running-imperatively/index.html | 4 ++-- docs/6.8.0/sanitization-chain-api/index.html | 4 ++-- docs/6.8.0/sanitization/index.html | 4 ++-- docs/6.8.0/schema-validation/index.html | 4 ++-- docs/6.8.0/validation-chain-api/index.html | 4 ++-- docs/6.8.0/validation-result-api/index.html | 4 ++-- docs/6.8.0/whole-body-validation/index.html | 4 ++-- docs/6.8.0/wildcards/index.html | 4 ++-- docs/6.9.0/check-api/index.html | 4 ++-- docs/6.9.0/custom-error-messages/index.html | 4 ++-- docs/6.9.0/custom-validators-sanitizers/index.html | 4 ++-- docs/6.9.0/filter-api/index.html | 4 ++-- docs/6.9.0/index.html | 4 ++-- docs/6.9.0/matched-data-api/index.html | 4 ++-- docs/6.9.0/running-imperatively/index.html | 4 ++-- docs/6.9.0/sanitization-chain-api/index.html | 4 ++-- docs/6.9.0/sanitization/index.html | 4 ++-- docs/6.9.0/schema-validation/index.html | 4 ++-- docs/6.9.0/validation-chain-api/index.html | 4 ++-- docs/6.9.0/validation-result-api/index.html | 4 ++-- docs/6.9.0/whole-body-validation/index.html | 4 ++-- docs/6.9.0/wildcards/index.html | 4 ++-- docs/api/check-exact/index.html | 4 ++-- docs/api/check-schema/index.html | 4 ++-- docs/api/check/index.html | 6 +++--- docs/api/express-validator/index.html | 6 +++--- docs/api/matched-data/index.html | 4 ++-- docs/api/misc/index.html | 4 ++-- docs/api/one-of/index.html | 4 ++-- docs/api/validation-chain/index.html | 4 ++-- docs/api/validation-result/index.html | 4 ++-- docs/architecture/index.html | 4 ++-- docs/category/guides/index.html | 4 ++-- docs/category/migrating/index.html | 4 ++-- docs/guides/customizing/index.html | 4 ++-- docs/guides/field-selection/index.html | 4 ++-- docs/guides/getting-started/index.html | 4 ++-- docs/guides/manually-running/index.html | 4 ++-- docs/guides/schema-validation/index.html | 4 ++-- docs/guides/validation-chain/index.html | 4 ++-- docs/index.html | 4 ++-- docs/migration-v5-to-v6/index.html | 4 ++-- docs/migration-v6-to-v7/index.html | 4 ++-- docs/next/api/check-exact/index.html | 4 ++-- docs/next/api/check-schema/index.html | 4 ++-- docs/next/api/check/index.html | 6 +++--- docs/next/api/express-validator/index.html | 6 +++--- docs/next/api/matched-data/index.html | 4 ++-- docs/next/api/misc/index.html | 4 ++-- docs/next/api/one-of/index.html | 4 ++-- docs/next/api/validation-chain/index.html | 4 ++-- docs/next/api/validation-result/index.html | 4 ++-- docs/next/architecture/index.html | 4 ++-- docs/next/category/guides/index.html | 4 ++-- docs/next/category/migrating/index.html | 4 ++-- docs/next/guides/customizing/index.html | 4 ++-- docs/next/guides/field-selection/index.html | 4 ++-- docs/next/guides/getting-started/index.html | 4 ++-- docs/next/guides/manually-running/index.html | 4 ++-- docs/next/guides/schema-validation/index.html | 4 ++-- docs/next/guides/validation-chain/index.html | 4 ++-- docs/next/index.html | 4 ++-- docs/next/migration-v5-to-v6/index.html | 4 ++-- docs/next/migration-v6-to-v7/index.html | 4 ++-- index.html | 4 ++-- search/index.html | 4 ++-- 314 files changed, 623 insertions(+), 623 deletions(-) rename assets/js/{4e289b8c.c33a8e6e.js => 4e289b8c.b2f5880a.js} (92%) rename assets/js/{609507dd.fc0c4e35.js => 609507dd.f2a4e177.js} (92%) create mode 100644 assets/js/60e2c3e9.e99e4a3b.js delete mode 100644 assets/js/60e2c3e9.eaaa856f.js delete mode 100644 assets/js/84854274.24286938.js create mode 100644 assets/js/84854274.82275863.js rename assets/js/{runtime~main.c46e207b.js => runtime~main.96406a10.js} (98%) diff --git a/404.html b/404.html index 42ef5d2..d4a4945 100644 --- a/404.html +++ b/404.html @@ -6,7 +6,7 @@ Page Not Found | express-validator - + @@ -14,7 +14,7 @@
Skip to main content

Page Not Found

We could not find what you were looking for.

Please contact the owner of the site that linked you to the original URL and let them know their link is broken.

- + \ No newline at end of file diff --git a/assets/js/4e289b8c.c33a8e6e.js b/assets/js/4e289b8c.b2f5880a.js similarity index 92% rename from assets/js/4e289b8c.c33a8e6e.js rename to assets/js/4e289b8c.b2f5880a.js index e840dfc..5fcbfd3 100644 --- a/assets/js/4e289b8c.c33a8e6e.js +++ b/assets/js/4e289b8c.b2f5880a.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6787],{5318:(e,a,t)=>{t.d(a,{Zo:()=>u,kt:()=>h});var n=t(7378);function r(e,a,t){return a in e?Object.defineProperty(e,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[a]=t,e}function i(e,a){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);a&&(n=n.filter((function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable}))),t.push.apply(t,n)}return t}function o(e){for(var a=1;a=0||(r[t]=e[t]);return r}(e,a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(r[t]=e[t])}return r}var s=n.createContext({}),c=function(e){var a=n.useContext(s),t=a;return e&&(t="function"==typeof e?e(a):o(o({},a),e)),t},u=function(e){var a=c(e.components);return n.createElement(s.Provider,{value:a},e.children)},d="mdxType",p={inlineCode:"code",wrapper:function(e){var a=e.children;return n.createElement(n.Fragment,{},a)}},m=n.forwardRef((function(e,a){var t=e.components,r=e.mdxType,i=e.originalType,s=e.parentName,u=l(e,["components","mdxType","originalType","parentName"]),d=c(t),m=r,h=d["".concat(s,".").concat(m)]||d[m]||p[m]||i;return t?n.createElement(h,o(o({ref:a},u),{},{components:t})):n.createElement(h,o({ref:a},u))}));function h(e,a){var t=arguments,r=a&&a.mdxType;if("string"==typeof e||r){var i=t.length,o=new Array(i);o[0]=m;var l={};for(var s in a)hasOwnProperty.call(a,s)&&(l[s]=a[s]);l.originalType=e,l[d]="string"==typeof e?e:r,o[1]=l;for(var c=2;c{t.d(a,{Z:()=>o});var n=t(7378),r=t(8944);const i="tabItem_wHwb";function o(e){var a=e.children,t=e.hidden,o=e.className;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i,o),hidden:t},a)}},3930:(e,a,t)=>{t.d(a,{Z:()=>C});var n=t(5773),r=t(7378),i=t(8944),o=t(3457),l=t(3620),s=t(654),c=t(784),u=t(1819);function d(e){return function(e){var a,t;return null!=(a=null==(t=r.Children.map(e,(function(e){if(!e||(0,r.isValidElement)(e)&&(a=e.props)&&"object"==typeof a&&"value"in a)return e;var a;throw new Error("Docusaurus error: Bad child <"+("string"==typeof e.type?e.type:e.type.name)+'>: all children of the component should be , and every should have a unique "value" prop.')})))?void 0:t.filter(Boolean))?a:[]}(e).map((function(e){var a=e.props;return{value:a.value,label:a.label,attributes:a.attributes,default:a.default}}))}function p(e){var a=e.values,t=e.children;return(0,r.useMemo)((function(){var e=null!=a?a:d(t);return function(e){var a=(0,c.l)(e,(function(e,a){return e.value===a.value}));if(a.length>0)throw new Error('Docusaurus error: Duplicate values "'+a.map((function(e){return e.value})).join(", ")+'" found in . Every value needs to be unique.')}(e),e}),[a,t])}function m(e){var a=e.value;return e.tabValues.some((function(e){return e.value===a}))}function h(e){var a=e.queryString,t=void 0!==a&&a,n=e.groupId,i=(0,l.k6)(),o=function(e){var a=e.queryString,t=void 0!==a&&a,n=e.groupId;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return null!=n?n:null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((function(e){if(o){var a=new URLSearchParams(i.location.search);a.set(o,e),i.replace(Object.assign({},i.location,{search:a.toString()}))}}),[o,i])]}function k(e){var a,t,n,i,o=e.defaultValue,l=e.queryString,s=void 0!==l&&l,c=e.groupId,d=p(e),k=(0,r.useState)((function(){return function(e){var a,t=e.defaultValue,n=e.tabValues;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error('Docusaurus error: The has a defaultValue "'+t+'" but none of its children has the corresponding value. Available values are: '+n.map((function(e){return e.value})).join(", ")+". If you intend to show no default tab, use defaultValue={null} instead.");return t}var r=null!=(a=n.find((function(e){return e.default})))?a:n[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:o,tabValues:d})})),f=k[0],v=k[1],y=h({queryString:s,groupId:c}),g=y[0],N=y[1],b=(a=function(e){return e?"docusaurus.tab."+e:null}({groupId:c}.groupId),t=(0,u.Nk)(a),n=t[0],i=t[1],[n,(0,r.useCallback)((function(e){a&&i.set(e)}),[a,i])]),C=b[0],E=b[1],x=function(){var e=null!=g?g:C;return m({value:e,tabValues:d})?e:null}();return(0,r.useLayoutEffect)((function(){x&&v(x)}),[x]),{selectedValue:f,selectValue:(0,r.useCallback)((function(e){if(!m({value:e,tabValues:d}))throw new Error("Can't select invalid tab value="+e);v(e),N(e),E(e)}),[N,E,d]),tabValues:d}}var f=t(6457);const v="tabList_J5MA",y="tabItem_l0OV";function g(e){var a=e.className,t=e.block,l=e.selectedValue,s=e.selectValue,c=e.tabValues,u=[],d=(0,o.o5)().blockElementScrollPositionUntilNextRender,p=function(e){var a=e.currentTarget,t=u.indexOf(a),n=c[t].value;n!==l&&(d(a),s(n))},m=function(e){var a,t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":var n,r=u.indexOf(e.currentTarget)+1;t=null!=(n=u[r])?n:u[0];break;case"ArrowLeft":var i,o=u.indexOf(e.currentTarget)-1;t=null!=(i=u[o])?i:u[u.length-1]}null==(a=t)||a.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":t},a)},c.map((function(e){var a=e.value,t=e.label,o=e.attributes;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:function(e){return u.push(e)},onKeyDown:m,onClick:p},o,{className:(0,i.Z)("tabs__item",y,null==o?void 0:o.className,{"tabs__item--active":l===a})}),null!=t?t:a)})))}function N(e){var a=e.lazy,t=e.children,n=e.selectedValue,i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){var o=i.find((function(e){return e.props.value===n}));return o?(0,r.cloneElement)(o,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map((function(e,a){return(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n})})))}function b(e){var a=k(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v)},r.createElement(g,(0,n.Z)({},e,a)),r.createElement(N,(0,n.Z)({},e,a)))}function C(e){var a=(0,f.Z)();return r.createElement(b,(0,n.Z)({key:String(a)},e))}},1222:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>u,default:()=>k,frontMatter:()=>c,metadata:()=>d,toc:()=>m});var n=t(5773),r=t(808),i=(t(7378),t(5318)),o=t(3930),l=t(9798),s=["components"],c={title:"ExpressValidator"},u="ExpressValidator",d={unversionedId:"api/express-validator",id:"version-7.0.0/api/express-validator",title:"ExpressValidator",description:"ExpressValidator",source:"@site/versioned_docs/version-7.0.0/api/express-validator.md",sourceDirName:"api",slug:"/api/express-validator",permalink:"/docs/api/express-validator",draft:!1,editUrl:"https://github.com/express-validator/express-validator/edit/master/docs/versioned_docs/version-7.0.0/api/express-validator.md",tags:[],version:"7.0.0",frontMatter:{title:"ExpressValidator"},sidebar:"api",previous:{title:"ValidationChain",permalink:"/docs/api/validation-chain"},next:{title:"matchedData",permalink:"/docs/api/matched-data"}},p={},m=[{value:"ExpressValidator",id:"expressvalidator",level:2},{value:"Usage",id:"usage",level:3},{value:"With custom validators only",id:"with-custom-validators-only",level:4},{value:"With custom sanitizers only",id:"with-custom-sanitizers-only",level:4},{value:".check()",id:"check",level:3},{value:".body()",id:"body",level:3},{value:".cookie()",id:"cookie",level:3},{value:".header()",id:"header",level:3},{value:".param()",id:"param",level:3},{value:".query()",id:"query",level:3},{value:".buildCheckFunction()",id:"buildcheckfunction",level:3},{value:".checkExact()",id:"checkexact",level:3},{value:".checkSchema()",id:"checkschema",level:3},{value:".matchedData()",id:"matcheddata",level:3},{value:".oneOf()",id:"oneof",level:3},{value:".validationResult()",id:"validationresult",level:3},{value:"CustomSchema",id:"customschema",level:2},{value:"CustomValidationChain",id:"customvalidationchain",level:2}],h={toc:m};function k(e){var a=e.components,t=(0,r.Z)(e,s);return(0,i.kt)("wrapper",(0,n.Z)({},h,t,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"expressvalidator"},(0,i.kt)("inlineCode",{parentName:"h1"},"ExpressValidator")),(0,i.kt)("h2",{id:"expressvalidator"},(0,i.kt)("inlineCode",{parentName:"h2"},"ExpressValidator")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator } from 'express-validator';\nnew ExpressValidator(\n customValidators?: Record,\n customSanitizers?: Record,\n options?: {\n errorFormatter: ErrorFormatter;\n }\n);\n")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," is a class which wraps the entire express-validator API, with some differences:"),(0,i.kt)("ol",null,(0,i.kt)("li",{parentName:"ol"},"you can specify custom validators and/or custom sanitizers that are always available in validation chains;"),(0,i.kt)("li",{parentName:"ol"},"you can specify options that apply by default to some functions.")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"customValidators")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"customSanitizers")," are objects from custom validator/sanitizer name to implementation.",(0,i.kt)("br",null),"\nSee examples in the ",(0,i.kt)("a",{parentName:"p",href:"#usage"},"usage section"),", and see the ",(0,i.kt)("a",{parentName:"p",href:"/docs/guides/customizing#custom-validators-and-sanitizers"},'"Custom Validators and Sanitizers" guide'),"\nto learn more."),(0,i.kt)("p",null,"If ",(0,i.kt)("inlineCode",{parentName:"p"},"options.errorFormatter")," is set, it's used as the default error formatter used by ",(0,i.kt)("a",{parentName:"p",href:"#validationresult"},(0,i.kt)("inlineCode",{parentName:"a"},".validationResult()")),"."),(0,i.kt)("h3",{id:"usage"},"Usage"),(0,i.kt)("h4",{id:"with-custom-validators-only"},"With custom validators only"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { body } = new ExpressValidator({\n isEmailNotInUse: async value => {\n const user = await Users.findByEmail(value);\n if (user) {\n throw new Error('E-mail already in use');\n }\n },\n});\n\napp.post('/signup', body('email').isEmailNotInUse(), (req, res) => {});\n")),(0,i.kt)("h4",{id:"with-custom-sanitizers-only"},"With custom sanitizers only"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { body } = new ExpressValidator({}, {\n muteOffensiveWords: async value => {\n for (const word of offensiveWords) {\n value = value.replaceAll(new RegExp(`\\\\b${word}\\\\b`), word[0].padEnd(word.length, '*'));\n }\n return value;\n },\n});\n\napp.post('/add-comment', body('comment').muteOffensiveWords(), (req, res) => {});\n")),(0,i.kt)("h3",{id:"check"},(0,i.kt)("inlineCode",{parentName:"h3"},".check()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"check(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#check"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"check()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"body"},(0,i.kt)("inlineCode",{parentName:"h3"},".body()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"body(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#body"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"body()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"cookie"},(0,i.kt)("inlineCode",{parentName:"h3"},".cookie()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"cookie(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#cookie"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"cookie()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"header"},(0,i.kt)("inlineCode",{parentName:"h3"},".header()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"header(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#header"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"header()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"param"},(0,i.kt)("inlineCode",{parentName:"h3"},".param()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"param(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#check"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"check()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"query"},(0,i.kt)("inlineCode",{parentName:"h3"},".query()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"query(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#query"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"query()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"buildcheckfunction"},(0,i.kt)("inlineCode",{parentName:"h3"},".buildCheckFunction()")),(0,i.kt)("h3",{id:"checkexact"},(0,i.kt)("inlineCode",{parentName:"h3"},".checkExact()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check-exact#checkexact"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"checkExact()")," function"),".\nOnly present in ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," for convenience."),(0,i.kt)("h3",{id:"checkschema"},(0,i.kt)("inlineCode",{parentName:"h3"},".checkSchema()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"checkSchema(schema: CustomSchema, defaultLocations?: Location[]): CustomValidationChain[]\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check-schema#checkschema"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"checkSchema()")," function"),", but the schema can reference\nthe custom validators or sanitizers from the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { checkSchema } = new ExpressValidator({ isEmailNotInUse });\napp.post(\n '/signup',\n checkSchema({\n email: { isEmailNotInUse: true },\n }),\n (req, res) => {\n // handle request\n },\n);\n")),(0,i.kt)("h3",{id:"matcheddata"},(0,i.kt)("inlineCode",{parentName:"h3"},".matchedData()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/matched-data"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"matchedData()")," function"),".\nOnly present in ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," for convenience."),(0,i.kt)("h3",{id:"oneof"},(0,i.kt)("inlineCode",{parentName:"h3"},".oneOf()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/one-of"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"oneOf()")," function"),", but accepts ",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"),"s"),"\ncreated from ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("h3",{id:"validationresult"},(0,i.kt)("inlineCode",{parentName:"h3"},".validationResult()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"validationResult(req): Result\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/validation-result#validationresult"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"validationResult()")," function"),",\nbut uses the ",(0,i.kt)("inlineCode",{parentName:"p"},"options.errorFormatter")," passed in the constructor by default."),(0,i.kt)(o.Z,{groupId:"lang",mdxType:"Tabs"},(0,i.kt)(l.Z,{value:"js",label:"JavaScript",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-js"},"const { ExpressValidator } = require('express-validator');\n\nconst { query, validationResult } = new ExpressValidator({}, {}, {\n errorFormatter: error => error.msg,\n};\n\napp.post('/hello', query('person').notEmpty(), (req, res) => {\n const result = validationResult(req);\n const errors = result.array();\n // => ['Invalid value', ... ]\n\n const result2 = result.formatWith(error => `${error.msg}!!!`);\n const errors2 = result2.array();\n // => ['Invalid value!!!']\n});\n"))),(0,i.kt)(l.Z,{value:"ts",label:"TypeScript",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { Result, ExpressValidator } from 'express-validator';\n\nconst { query, validationResult } = new ExpressValidator({}, {}, {\n errorFormatter: error => error.msg as string,\n};\n\napp.post('/hello', query('person').notEmpty(), (req, res) => {\n const result: Result = validationResult(req);\n const errors = result.array();\n // => ['Invalid value', ... ]\n\n const result2: Result = result.formatWith(error => `${error.msg}!!!`);\n const errors2 = result2.array();\n // => ['Invalid value!!!']\n});\n")))),(0,i.kt)("h2",{id:"customschema"},(0,i.kt)("inlineCode",{parentName:"h2"},"CustomSchema")),(0,i.kt)("p",null,"The type of a schema created through ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("p",null,"Has a single generic parameter ",(0,i.kt)("inlineCode",{parentName:"p"},"T"),", which is the type of the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator, CustomSchema } from 'express-validator';\n\nconst myExpressValidator = new ExpressValidator({ isEmailNotInUse });\ntype MyCustomSchema = CustomSchema;\n\nconst schema: MyCustomSchema = {\n email: { isEmailNotInUse: true },\n};\n")),(0,i.kt)("h2",{id:"customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"h2"},"CustomValidationChain")),(0,i.kt)("p",null,"The type of a validation chain created through ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("p",null,"Has a single generic parameter ",(0,i.kt)("inlineCode",{parentName:"p"},"T"),", which is the type of the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator, CustomValidationChain } from 'express-validator';\n\nconst myExpressValidator = new ExpressValidator({ isEmailNotInUse });\ntype MyValidationChain = CustomValidationChain;\n\nconst chain: MyValidationChain = myExpressValidator.body('email').isEmailNotInUse();\n")))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[6787],{5318:(e,a,t)=>{t.d(a,{Zo:()=>c,kt:()=>h});var n=t(7378);function r(e,a,t){return a in e?Object.defineProperty(e,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[a]=t,e}function i(e,a){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);a&&(n=n.filter((function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable}))),t.push.apply(t,n)}return t}function o(e){for(var a=1;a=0||(r[t]=e[t]);return r}(e,a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(r[t]=e[t])}return r}var s=n.createContext({}),u=function(e){var a=n.useContext(s),t=a;return e&&(t="function"==typeof e?e(a):o(o({},a),e)),t},c=function(e){var a=u(e.components);return n.createElement(s.Provider,{value:a},e.children)},d="mdxType",p={inlineCode:"code",wrapper:function(e){var a=e.children;return n.createElement(n.Fragment,{},a)}},m=n.forwardRef((function(e,a){var t=e.components,r=e.mdxType,i=e.originalType,s=e.parentName,c=l(e,["components","mdxType","originalType","parentName"]),d=u(t),m=r,h=d["".concat(s,".").concat(m)]||d[m]||p[m]||i;return t?n.createElement(h,o(o({ref:a},c),{},{components:t})):n.createElement(h,o({ref:a},c))}));function h(e,a){var t=arguments,r=a&&a.mdxType;if("string"==typeof e||r){var i=t.length,o=new Array(i);o[0]=m;var l={};for(var s in a)hasOwnProperty.call(a,s)&&(l[s]=a[s]);l.originalType=e,l[d]="string"==typeof e?e:r,o[1]=l;for(var u=2;u{t.d(a,{Z:()=>o});var n=t(7378),r=t(8944);const i="tabItem_wHwb";function o(e){var a=e.children,t=e.hidden,o=e.className;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i,o),hidden:t},a)}},3930:(e,a,t)=>{t.d(a,{Z:()=>C});var n=t(5773),r=t(7378),i=t(8944),o=t(3457),l=t(3620),s=t(654),u=t(784),c=t(1819);function d(e){return function(e){var a,t;return null!=(a=null==(t=r.Children.map(e,(function(e){if(!e||(0,r.isValidElement)(e)&&(a=e.props)&&"object"==typeof a&&"value"in a)return e;var a;throw new Error("Docusaurus error: Bad child <"+("string"==typeof e.type?e.type:e.type.name)+'>: all children of the component should be , and every should have a unique "value" prop.')})))?void 0:t.filter(Boolean))?a:[]}(e).map((function(e){var a=e.props;return{value:a.value,label:a.label,attributes:a.attributes,default:a.default}}))}function p(e){var a=e.values,t=e.children;return(0,r.useMemo)((function(){var e=null!=a?a:d(t);return function(e){var a=(0,u.l)(e,(function(e,a){return e.value===a.value}));if(a.length>0)throw new Error('Docusaurus error: Duplicate values "'+a.map((function(e){return e.value})).join(", ")+'" found in . Every value needs to be unique.')}(e),e}),[a,t])}function m(e){var a=e.value;return e.tabValues.some((function(e){return e.value===a}))}function h(e){var a=e.queryString,t=void 0!==a&&a,n=e.groupId,i=(0,l.k6)(),o=function(e){var a=e.queryString,t=void 0!==a&&a,n=e.groupId;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return null!=n?n:null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((function(e){if(o){var a=new URLSearchParams(i.location.search);a.set(o,e),i.replace(Object.assign({},i.location,{search:a.toString()}))}}),[o,i])]}function k(e){var a,t,n,i,o=e.defaultValue,l=e.queryString,s=void 0!==l&&l,u=e.groupId,d=p(e),k=(0,r.useState)((function(){return function(e){var a,t=e.defaultValue,n=e.tabValues;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error('Docusaurus error: The has a defaultValue "'+t+'" but none of its children has the corresponding value. Available values are: '+n.map((function(e){return e.value})).join(", ")+". If you intend to show no default tab, use defaultValue={null} instead.");return t}var r=null!=(a=n.find((function(e){return e.default})))?a:n[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:o,tabValues:d})})),f=k[0],v=k[1],y=h({queryString:s,groupId:u}),g=y[0],N=y[1],b=(a=function(e){return e?"docusaurus.tab."+e:null}({groupId:u}.groupId),t=(0,c.Nk)(a),n=t[0],i=t[1],[n,(0,r.useCallback)((function(e){a&&i.set(e)}),[a,i])]),C=b[0],E=b[1],x=function(){var e=null!=g?g:C;return m({value:e,tabValues:d})?e:null}();return(0,r.useLayoutEffect)((function(){x&&v(x)}),[x]),{selectedValue:f,selectValue:(0,r.useCallback)((function(e){if(!m({value:e,tabValues:d}))throw new Error("Can't select invalid tab value="+e);v(e),N(e),E(e)}),[N,E,d]),tabValues:d}}var f=t(6457);const v="tabList_J5MA",y="tabItem_l0OV";function g(e){var a=e.className,t=e.block,l=e.selectedValue,s=e.selectValue,u=e.tabValues,c=[],d=(0,o.o5)().blockElementScrollPositionUntilNextRender,p=function(e){var a=e.currentTarget,t=c.indexOf(a),n=u[t].value;n!==l&&(d(a),s(n))},m=function(e){var a,t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":var n,r=c.indexOf(e.currentTarget)+1;t=null!=(n=c[r])?n:c[0];break;case"ArrowLeft":var i,o=c.indexOf(e.currentTarget)-1;t=null!=(i=c[o])?i:c[c.length-1]}null==(a=t)||a.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":t},a)},u.map((function(e){var a=e.value,t=e.label,o=e.attributes;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:function(e){return c.push(e)},onKeyDown:m,onClick:p},o,{className:(0,i.Z)("tabs__item",y,null==o?void 0:o.className,{"tabs__item--active":l===a})}),null!=t?t:a)})))}function N(e){var a=e.lazy,t=e.children,n=e.selectedValue,i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){var o=i.find((function(e){return e.props.value===n}));return o?(0,r.cloneElement)(o,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map((function(e,a){return(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n})})))}function b(e){var a=k(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v)},r.createElement(g,(0,n.Z)({},e,a)),r.createElement(N,(0,n.Z)({},e,a)))}function C(e){var a=(0,f.Z)();return r.createElement(b,(0,n.Z)({key:String(a)},e))}},1222:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>c,default:()=>k,frontMatter:()=>u,metadata:()=>d,toc:()=>m});var n=t(5773),r=t(808),i=(t(7378),t(5318)),o=t(3930),l=t(9798),s=["components"],u={title:"ExpressValidator"},c="ExpressValidator",d={unversionedId:"api/express-validator",id:"version-7.0.0/api/express-validator",title:"ExpressValidator",description:"ExpressValidator",source:"@site/versioned_docs/version-7.0.0/api/express-validator.md",sourceDirName:"api",slug:"/api/express-validator",permalink:"/docs/api/express-validator",draft:!1,editUrl:"https://github.com/express-validator/express-validator/edit/master/docs/versioned_docs/version-7.0.0/api/express-validator.md",tags:[],version:"7.0.0",frontMatter:{title:"ExpressValidator"},sidebar:"api",previous:{title:"ValidationChain",permalink:"/docs/api/validation-chain"},next:{title:"matchedData",permalink:"/docs/api/matched-data"}},p={},m=[{value:"ExpressValidator",id:"expressvalidator",level:2},{value:"Usage",id:"usage",level:3},{value:"With custom validators only",id:"with-custom-validators-only",level:4},{value:"With custom sanitizers only",id:"with-custom-sanitizers-only",level:4},{value:".check()",id:"check",level:3},{value:".body()",id:"body",level:3},{value:".cookie()",id:"cookie",level:3},{value:".header()",id:"header",level:3},{value:".param()",id:"param",level:3},{value:".query()",id:"query",level:3},{value:".buildCheckFunction()",id:"buildcheckfunction",level:3},{value:".checkExact()",id:"checkexact",level:3},{value:".checkSchema()",id:"checkschema",level:3},{value:".matchedData()",id:"matcheddata",level:3},{value:".oneOf()",id:"oneof",level:3},{value:".validationResult()",id:"validationresult",level:3},{value:"CustomSchema",id:"customschema",level:2},{value:"CustomValidationChain",id:"customvalidationchain",level:2}],h={toc:m};function k(e){var a=e.components,t=(0,r.Z)(e,s);return(0,i.kt)("wrapper",(0,n.Z)({},h,t,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"expressvalidator"},(0,i.kt)("inlineCode",{parentName:"h1"},"ExpressValidator")),(0,i.kt)("h2",{id:"expressvalidator"},(0,i.kt)("inlineCode",{parentName:"h2"},"ExpressValidator")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator } from 'express-validator';\nnew ExpressValidator(\n customValidators?: Record,\n customSanitizers?: Record,\n options?: {\n errorFormatter: ErrorFormatter;\n }\n);\n")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," is a class which wraps the entire express-validator API, with some differences:"),(0,i.kt)("ol",null,(0,i.kt)("li",{parentName:"ol"},"you can specify custom validators and/or custom sanitizers that are always available in validation chains;"),(0,i.kt)("li",{parentName:"ol"},"you can specify options that apply by default to some functions.")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"customValidators")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"customSanitizers")," are objects from custom validator/sanitizer name to implementation.",(0,i.kt)("br",null),"\nSee examples in the ",(0,i.kt)("a",{parentName:"p",href:"#usage"},"usage section"),", and see the ",(0,i.kt)("a",{parentName:"p",href:"/docs/guides/customizing#custom-validators-and-sanitizers"},'"Custom Validators and Sanitizers" guide'),"\nto learn more."),(0,i.kt)("p",null,"If ",(0,i.kt)("inlineCode",{parentName:"p"},"options.errorFormatter")," is set, it's used as the default error formatter used by ",(0,i.kt)("a",{parentName:"p",href:"#validationresult"},(0,i.kt)("inlineCode",{parentName:"a"},".validationResult()")),"."),(0,i.kt)("h3",{id:"usage"},"Usage"),(0,i.kt)("h4",{id:"with-custom-validators-only"},"With custom validators only"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { body } = new ExpressValidator({\n isEmailNotInUse: async value => {\n const user = await Users.findByEmail(value);\n if (user) {\n throw new Error('E-mail already in use');\n }\n },\n});\n\napp.post('/signup', body('email').isEmailNotInUse(), (req, res) => {});\n")),(0,i.kt)("h4",{id:"with-custom-sanitizers-only"},"With custom sanitizers only"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { body } = new ExpressValidator({}, {\n muteOffensiveWords: async value => {\n for (const word of offensiveWords) {\n value = value.replaceAll(new RegExp(`\\\\b${word}\\\\b`), word[0].padEnd(word.length, '*'));\n }\n return value;\n },\n});\n\napp.post('/add-comment', body('comment').muteOffensiveWords(), (req, res) => {});\n")),(0,i.kt)("h3",{id:"check"},(0,i.kt)("inlineCode",{parentName:"h3"},".check()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"check(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#check"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"check()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"body"},(0,i.kt)("inlineCode",{parentName:"h3"},".body()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"body(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#body"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"body()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"cookie"},(0,i.kt)("inlineCode",{parentName:"h3"},".cookie()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"cookie(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#cookie"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"cookie()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"header"},(0,i.kt)("inlineCode",{parentName:"h3"},".header()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"header(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#header"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"header()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"param"},(0,i.kt)("inlineCode",{parentName:"h3"},".param()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"param(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#param"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"param()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"query"},(0,i.kt)("inlineCode",{parentName:"h3"},".query()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"query(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check#query"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"query()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"buildcheckfunction"},(0,i.kt)("inlineCode",{parentName:"h3"},".buildCheckFunction()")),(0,i.kt)("h3",{id:"checkexact"},(0,i.kt)("inlineCode",{parentName:"h3"},".checkExact()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check-exact#checkexact"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"checkExact()")," function"),".\nOnly present in ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," for convenience."),(0,i.kt)("h3",{id:"checkschema"},(0,i.kt)("inlineCode",{parentName:"h3"},".checkSchema()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"checkSchema(schema: CustomSchema, defaultLocations?: Location[]): CustomValidationChain[]\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/check-schema#checkschema"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"checkSchema()")," function"),", but the schema can reference\nthe custom validators or sanitizers from the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { checkSchema } = new ExpressValidator({ isEmailNotInUse });\napp.post(\n '/signup',\n checkSchema({\n email: { isEmailNotInUse: true },\n }),\n (req, res) => {\n // handle request\n },\n);\n")),(0,i.kt)("h3",{id:"matcheddata"},(0,i.kt)("inlineCode",{parentName:"h3"},".matchedData()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/matched-data"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"matchedData()")," function"),".\nOnly present in ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," for convenience."),(0,i.kt)("h3",{id:"oneof"},(0,i.kt)("inlineCode",{parentName:"h3"},".oneOf()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/one-of"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"oneOf()")," function"),", but accepts ",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"),"s"),"\ncreated from ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("h3",{id:"validationresult"},(0,i.kt)("inlineCode",{parentName:"h3"},".validationResult()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"validationResult(req): Result\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/validation-result#validationresult"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"validationResult()")," function"),",\nbut uses the ",(0,i.kt)("inlineCode",{parentName:"p"},"options.errorFormatter")," passed in the constructor by default."),(0,i.kt)(o.Z,{groupId:"lang",mdxType:"Tabs"},(0,i.kt)(l.Z,{value:"js",label:"JavaScript",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-js"},"const { ExpressValidator } = require('express-validator');\n\nconst { query, validationResult } = new ExpressValidator({}, {}, {\n errorFormatter: error => error.msg,\n};\n\napp.post('/hello', query('person').notEmpty(), (req, res) => {\n const result = validationResult(req);\n const errors = result.array();\n // => ['Invalid value', ... ]\n\n const result2 = result.formatWith(error => `${error.msg}!!!`);\n const errors2 = result2.array();\n // => ['Invalid value!!!']\n});\n"))),(0,i.kt)(l.Z,{value:"ts",label:"TypeScript",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { Result, ExpressValidator } from 'express-validator';\n\nconst { query, validationResult } = new ExpressValidator({}, {}, {\n errorFormatter: error => error.msg as string,\n};\n\napp.post('/hello', query('person').notEmpty(), (req, res) => {\n const result: Result = validationResult(req);\n const errors = result.array();\n // => ['Invalid value', ... ]\n\n const result2: Result = result.formatWith(error => `${error.msg}!!!`);\n const errors2 = result2.array();\n // => ['Invalid value!!!']\n});\n")))),(0,i.kt)("h2",{id:"customschema"},(0,i.kt)("inlineCode",{parentName:"h2"},"CustomSchema")),(0,i.kt)("p",null,"The type of a schema created through ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("p",null,"Has a single generic parameter ",(0,i.kt)("inlineCode",{parentName:"p"},"T"),", which is the type of the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator, CustomSchema } from 'express-validator';\n\nconst myExpressValidator = new ExpressValidator({ isEmailNotInUse });\ntype MyCustomSchema = CustomSchema;\n\nconst schema: MyCustomSchema = {\n email: { isEmailNotInUse: true },\n};\n")),(0,i.kt)("h2",{id:"customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"h2"},"CustomValidationChain")),(0,i.kt)("p",null,"The type of a validation chain created through ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("p",null,"Has a single generic parameter ",(0,i.kt)("inlineCode",{parentName:"p"},"T"),", which is the type of the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator, CustomValidationChain } from 'express-validator';\n\nconst myExpressValidator = new ExpressValidator({ isEmailNotInUse });\ntype MyValidationChain = CustomValidationChain;\n\nconst chain: MyValidationChain = myExpressValidator.body('email').isEmailNotInUse();\n")))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/609507dd.fc0c4e35.js b/assets/js/609507dd.f2a4e177.js similarity index 92% rename from assets/js/609507dd.fc0c4e35.js rename to assets/js/609507dd.f2a4e177.js index 9ac4988..624a7f1 100644 --- a/assets/js/609507dd.fc0c4e35.js +++ b/assets/js/609507dd.f2a4e177.js @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2803],{5318:(e,a,t)=>{t.d(a,{Zo:()=>u,kt:()=>h});var n=t(7378);function r(e,a,t){return a in e?Object.defineProperty(e,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[a]=t,e}function i(e,a){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);a&&(n=n.filter((function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable}))),t.push.apply(t,n)}return t}function o(e){for(var a=1;a=0||(r[t]=e[t]);return r}(e,a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(r[t]=e[t])}return r}var s=n.createContext({}),c=function(e){var a=n.useContext(s),t=a;return e&&(t="function"==typeof e?e(a):o(o({},a),e)),t},u=function(e){var a=c(e.components);return n.createElement(s.Provider,{value:a},e.children)},d="mdxType",p={inlineCode:"code",wrapper:function(e){var a=e.children;return n.createElement(n.Fragment,{},a)}},m=n.forwardRef((function(e,a){var t=e.components,r=e.mdxType,i=e.originalType,s=e.parentName,u=l(e,["components","mdxType","originalType","parentName"]),d=c(t),m=r,h=d["".concat(s,".").concat(m)]||d[m]||p[m]||i;return t?n.createElement(h,o(o({ref:a},u),{},{components:t})):n.createElement(h,o({ref:a},u))}));function h(e,a){var t=arguments,r=a&&a.mdxType;if("string"==typeof e||r){var i=t.length,o=new Array(i);o[0]=m;var l={};for(var s in a)hasOwnProperty.call(a,s)&&(l[s]=a[s]);l.originalType=e,l[d]="string"==typeof e?e:r,o[1]=l;for(var c=2;c{t.d(a,{Z:()=>o});var n=t(7378),r=t(8944);const i="tabItem_wHwb";function o(e){var a=e.children,t=e.hidden,o=e.className;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i,o),hidden:t},a)}},3930:(e,a,t)=>{t.d(a,{Z:()=>C});var n=t(5773),r=t(7378),i=t(8944),o=t(3457),l=t(3620),s=t(654),c=t(784),u=t(1819);function d(e){return function(e){var a,t;return null!=(a=null==(t=r.Children.map(e,(function(e){if(!e||(0,r.isValidElement)(e)&&(a=e.props)&&"object"==typeof a&&"value"in a)return e;var a;throw new Error("Docusaurus error: Bad child <"+("string"==typeof e.type?e.type:e.type.name)+'>: all children of the component should be , and every should have a unique "value" prop.')})))?void 0:t.filter(Boolean))?a:[]}(e).map((function(e){var a=e.props;return{value:a.value,label:a.label,attributes:a.attributes,default:a.default}}))}function p(e){var a=e.values,t=e.children;return(0,r.useMemo)((function(){var e=null!=a?a:d(t);return function(e){var a=(0,c.l)(e,(function(e,a){return e.value===a.value}));if(a.length>0)throw new Error('Docusaurus error: Duplicate values "'+a.map((function(e){return e.value})).join(", ")+'" found in . Every value needs to be unique.')}(e),e}),[a,t])}function m(e){var a=e.value;return e.tabValues.some((function(e){return e.value===a}))}function h(e){var a=e.queryString,t=void 0!==a&&a,n=e.groupId,i=(0,l.k6)(),o=function(e){var a=e.queryString,t=void 0!==a&&a,n=e.groupId;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return null!=n?n:null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((function(e){if(o){var a=new URLSearchParams(i.location.search);a.set(o,e),i.replace(Object.assign({},i.location,{search:a.toString()}))}}),[o,i])]}function k(e){var a,t,n,i,o=e.defaultValue,l=e.queryString,s=void 0!==l&&l,c=e.groupId,d=p(e),k=(0,r.useState)((function(){return function(e){var a,t=e.defaultValue,n=e.tabValues;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error('Docusaurus error: The has a defaultValue "'+t+'" but none of its children has the corresponding value. Available values are: '+n.map((function(e){return e.value})).join(", ")+". If you intend to show no default tab, use defaultValue={null} instead.");return t}var r=null!=(a=n.find((function(e){return e.default})))?a:n[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:o,tabValues:d})})),f=k[0],v=k[1],y=h({queryString:s,groupId:c}),g=y[0],N=y[1],b=(a=function(e){return e?"docusaurus.tab."+e:null}({groupId:c}.groupId),t=(0,u.Nk)(a),n=t[0],i=t[1],[n,(0,r.useCallback)((function(e){a&&i.set(e)}),[a,i])]),C=b[0],x=b[1],E=function(){var e=null!=g?g:C;return m({value:e,tabValues:d})?e:null}();return(0,r.useLayoutEffect)((function(){E&&v(E)}),[E]),{selectedValue:f,selectValue:(0,r.useCallback)((function(e){if(!m({value:e,tabValues:d}))throw new Error("Can't select invalid tab value="+e);v(e),N(e),x(e)}),[N,x,d]),tabValues:d}}var f=t(6457);const v="tabList_J5MA",y="tabItem_l0OV";function g(e){var a=e.className,t=e.block,l=e.selectedValue,s=e.selectValue,c=e.tabValues,u=[],d=(0,o.o5)().blockElementScrollPositionUntilNextRender,p=function(e){var a=e.currentTarget,t=u.indexOf(a),n=c[t].value;n!==l&&(d(a),s(n))},m=function(e){var a,t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":var n,r=u.indexOf(e.currentTarget)+1;t=null!=(n=u[r])?n:u[0];break;case"ArrowLeft":var i,o=u.indexOf(e.currentTarget)-1;t=null!=(i=u[o])?i:u[u.length-1]}null==(a=t)||a.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":t},a)},c.map((function(e){var a=e.value,t=e.label,o=e.attributes;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:function(e){return u.push(e)},onKeyDown:m,onClick:p},o,{className:(0,i.Z)("tabs__item",y,null==o?void 0:o.className,{"tabs__item--active":l===a})}),null!=t?t:a)})))}function N(e){var a=e.lazy,t=e.children,n=e.selectedValue,i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){var o=i.find((function(e){return e.props.value===n}));return o?(0,r.cloneElement)(o,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map((function(e,a){return(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n})})))}function b(e){var a=k(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v)},r.createElement(g,(0,n.Z)({},e,a)),r.createElement(N,(0,n.Z)({},e,a)))}function C(e){var a=(0,f.Z)();return r.createElement(b,(0,n.Z)({key:String(a)},e))}},546:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>u,default:()=>k,frontMatter:()=>c,metadata:()=>d,toc:()=>m});var n=t(5773),r=t(808),i=(t(7378),t(5318)),o=t(3930),l=t(9798),s=["components"],c={title:"ExpressValidator"},u="ExpressValidator",d={unversionedId:"api/express-validator",id:"api/express-validator",title:"ExpressValidator",description:"ExpressValidator",source:"@site/../docs/api/express-validator.md",sourceDirName:"api",slug:"/api/express-validator",permalink:"/docs/next/api/express-validator",draft:!1,editUrl:"https://github.com/express-validator/express-validator/edit/master/docs/../docs/api/express-validator.md",tags:[],version:"current",frontMatter:{title:"ExpressValidator"},sidebar:"api",previous:{title:"ValidationChain",permalink:"/docs/next/api/validation-chain"},next:{title:"matchedData",permalink:"/docs/next/api/matched-data"}},p={},m=[{value:"ExpressValidator",id:"expressvalidator",level:2},{value:"Usage",id:"usage",level:3},{value:"With custom validators only",id:"with-custom-validators-only",level:4},{value:"With custom sanitizers only",id:"with-custom-sanitizers-only",level:4},{value:".check()",id:"check",level:3},{value:".body()",id:"body",level:3},{value:".cookie()",id:"cookie",level:3},{value:".header()",id:"header",level:3},{value:".param()",id:"param",level:3},{value:".query()",id:"query",level:3},{value:".buildCheckFunction()",id:"buildcheckfunction",level:3},{value:".checkExact()",id:"checkexact",level:3},{value:".checkSchema()",id:"checkschema",level:3},{value:".matchedData()",id:"matcheddata",level:3},{value:".oneOf()",id:"oneof",level:3},{value:".validationResult()",id:"validationresult",level:3},{value:"CustomSchema",id:"customschema",level:2},{value:"CustomValidationChain",id:"customvalidationchain",level:2}],h={toc:m};function k(e){var a=e.components,t=(0,r.Z)(e,s);return(0,i.kt)("wrapper",(0,n.Z)({},h,t,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"expressvalidator"},(0,i.kt)("inlineCode",{parentName:"h1"},"ExpressValidator")),(0,i.kt)("h2",{id:"expressvalidator"},(0,i.kt)("inlineCode",{parentName:"h2"},"ExpressValidator")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator } from 'express-validator';\nnew ExpressValidator(\n customValidators?: Record,\n customSanitizers?: Record,\n options?: {\n errorFormatter: ErrorFormatter;\n }\n);\n")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," is a class which wraps the entire express-validator API, with some differences:"),(0,i.kt)("ol",null,(0,i.kt)("li",{parentName:"ol"},"you can specify custom validators and/or custom sanitizers that are always available in validation chains;"),(0,i.kt)("li",{parentName:"ol"},"you can specify options that apply by default to some functions.")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"customValidators")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"customSanitizers")," are objects from custom validator/sanitizer name to implementation.",(0,i.kt)("br",null),"\nSee examples in the ",(0,i.kt)("a",{parentName:"p",href:"#usage"},"usage section"),", and see the ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/guides/customizing#custom-validators-and-sanitizers"},'"Custom Validators and Sanitizers" guide'),"\nto learn more."),(0,i.kt)("p",null,"If ",(0,i.kt)("inlineCode",{parentName:"p"},"options.errorFormatter")," is set, it's used as the default error formatter used by ",(0,i.kt)("a",{parentName:"p",href:"#validationresult"},(0,i.kt)("inlineCode",{parentName:"a"},".validationResult()")),"."),(0,i.kt)("h3",{id:"usage"},"Usage"),(0,i.kt)("h4",{id:"with-custom-validators-only"},"With custom validators only"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { body } = new ExpressValidator({\n isEmailNotInUse: async value => {\n const user = await Users.findByEmail(value);\n if (user) {\n throw new Error('E-mail already in use');\n }\n },\n});\n\napp.post('/signup', body('email').isEmailNotInUse(), (req, res) => {});\n")),(0,i.kt)("h4",{id:"with-custom-sanitizers-only"},"With custom sanitizers only"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { body } = new ExpressValidator({}, {\n muteOffensiveWords: async value => {\n for (const word of offensiveWords) {\n value = value.replaceAll(new RegExp(`\\\\b${word}\\\\b`), word[0].padEnd(word.length, '*'));\n }\n return value;\n },\n});\n\napp.post('/add-comment', body('comment').muteOffensiveWords(), (req, res) => {});\n")),(0,i.kt)("h3",{id:"check"},(0,i.kt)("inlineCode",{parentName:"h3"},".check()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"check(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#check"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"check()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"body"},(0,i.kt)("inlineCode",{parentName:"h3"},".body()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"body(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#body"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"body()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"cookie"},(0,i.kt)("inlineCode",{parentName:"h3"},".cookie()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"cookie(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#cookie"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"cookie()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"header"},(0,i.kt)("inlineCode",{parentName:"h3"},".header()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"header(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#header"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"header()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"param"},(0,i.kt)("inlineCode",{parentName:"h3"},".param()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"param(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#check"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"check()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"query"},(0,i.kt)("inlineCode",{parentName:"h3"},".query()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"query(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#query"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"query()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"buildcheckfunction"},(0,i.kt)("inlineCode",{parentName:"h3"},".buildCheckFunction()")),(0,i.kt)("h3",{id:"checkexact"},(0,i.kt)("inlineCode",{parentName:"h3"},".checkExact()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check-exact#checkexact"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"checkExact()")," function"),".\nOnly present in ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," for convenience."),(0,i.kt)("h3",{id:"checkschema"},(0,i.kt)("inlineCode",{parentName:"h3"},".checkSchema()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"checkSchema(schema: CustomSchema, defaultLocations?: Location[]): CustomValidationChain[]\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check-schema#checkschema"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"checkSchema()")," function"),", but the schema can reference\nthe custom validators or sanitizers from the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { checkSchema } = new ExpressValidator({ isEmailNotInUse });\napp.post(\n '/signup',\n checkSchema({\n email: { isEmailNotInUse: true },\n }),\n (req, res) => {\n // handle request\n },\n);\n")),(0,i.kt)("h3",{id:"matcheddata"},(0,i.kt)("inlineCode",{parentName:"h3"},".matchedData()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/matched-data"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"matchedData()")," function"),".\nOnly present in ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," for convenience."),(0,i.kt)("h3",{id:"oneof"},(0,i.kt)("inlineCode",{parentName:"h3"},".oneOf()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/one-of"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"oneOf()")," function"),", but accepts ",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"),"s"),"\ncreated from ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("h3",{id:"validationresult"},(0,i.kt)("inlineCode",{parentName:"h3"},".validationResult()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"validationResult(req): Result\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/validation-result#validationresult"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"validationResult()")," function"),",\nbut uses the ",(0,i.kt)("inlineCode",{parentName:"p"},"options.errorFormatter")," passed in the constructor by default."),(0,i.kt)(o.Z,{groupId:"lang",mdxType:"Tabs"},(0,i.kt)(l.Z,{value:"js",label:"JavaScript",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-js"},"const { ExpressValidator } = require('express-validator');\n\nconst { query, validationResult } = new ExpressValidator({}, {}, {\n errorFormatter: error => error.msg,\n};\n\napp.post('/hello', query('person').notEmpty(), (req, res) => {\n const result = validationResult(req);\n const errors = result.array();\n // => ['Invalid value', ... ]\n\n const result2 = result.formatWith(error => `${error.msg}!!!`);\n const errors2 = result2.array();\n // => ['Invalid value!!!']\n});\n"))),(0,i.kt)(l.Z,{value:"ts",label:"TypeScript",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { Result, ExpressValidator } from 'express-validator';\n\nconst { query, validationResult } = new ExpressValidator({}, {}, {\n errorFormatter: error => error.msg as string,\n};\n\napp.post('/hello', query('person').notEmpty(), (req, res) => {\n const result: Result = validationResult(req);\n const errors = result.array();\n // => ['Invalid value', ... ]\n\n const result2: Result = result.formatWith(error => `${error.msg}!!!`);\n const errors2 = result2.array();\n // => ['Invalid value!!!']\n});\n")))),(0,i.kt)("h2",{id:"customschema"},(0,i.kt)("inlineCode",{parentName:"h2"},"CustomSchema")),(0,i.kt)("p",null,"The type of a schema created through ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("p",null,"Has a single generic parameter ",(0,i.kt)("inlineCode",{parentName:"p"},"T"),", which is the type of the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator, CustomSchema } from 'express-validator';\n\nconst myExpressValidator = new ExpressValidator({ isEmailNotInUse });\ntype MyCustomSchema = CustomSchema;\n\nconst schema: MyCustomSchema = {\n email: { isEmailNotInUse: true },\n};\n")),(0,i.kt)("h2",{id:"customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"h2"},"CustomValidationChain")),(0,i.kt)("p",null,"The type of a validation chain created through ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("p",null,"Has a single generic parameter ",(0,i.kt)("inlineCode",{parentName:"p"},"T"),", which is the type of the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator, CustomValidationChain } from 'express-validator';\n\nconst myExpressValidator = new ExpressValidator({ isEmailNotInUse });\ntype MyValidationChain = CustomValidationChain;\n\nconst chain: MyValidationChain = myExpressValidator.body('email').isEmailNotInUse();\n")))}k.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[2803],{5318:(e,a,t)=>{t.d(a,{Zo:()=>c,kt:()=>h});var n=t(7378);function r(e,a,t){return a in e?Object.defineProperty(e,a,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[a]=t,e}function i(e,a){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);a&&(n=n.filter((function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable}))),t.push.apply(t,n)}return t}function o(e){for(var a=1;a=0||(r[t]=e[t]);return r}(e,a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(r[t]=e[t])}return r}var s=n.createContext({}),u=function(e){var a=n.useContext(s),t=a;return e&&(t="function"==typeof e?e(a):o(o({},a),e)),t},c=function(e){var a=u(e.components);return n.createElement(s.Provider,{value:a},e.children)},d="mdxType",p={inlineCode:"code",wrapper:function(e){var a=e.children;return n.createElement(n.Fragment,{},a)}},m=n.forwardRef((function(e,a){var t=e.components,r=e.mdxType,i=e.originalType,s=e.parentName,c=l(e,["components","mdxType","originalType","parentName"]),d=u(t),m=r,h=d["".concat(s,".").concat(m)]||d[m]||p[m]||i;return t?n.createElement(h,o(o({ref:a},c),{},{components:t})):n.createElement(h,o({ref:a},c))}));function h(e,a){var t=arguments,r=a&&a.mdxType;if("string"==typeof e||r){var i=t.length,o=new Array(i);o[0]=m;var l={};for(var s in a)hasOwnProperty.call(a,s)&&(l[s]=a[s]);l.originalType=e,l[d]="string"==typeof e?e:r,o[1]=l;for(var u=2;u{t.d(a,{Z:()=>o});var n=t(7378),r=t(8944);const i="tabItem_wHwb";function o(e){var a=e.children,t=e.hidden,o=e.className;return n.createElement("div",{role:"tabpanel",className:(0,r.Z)(i,o),hidden:t},a)}},3930:(e,a,t)=>{t.d(a,{Z:()=>C});var n=t(5773),r=t(7378),i=t(8944),o=t(3457),l=t(3620),s=t(654),u=t(784),c=t(1819);function d(e){return function(e){var a,t;return null!=(a=null==(t=r.Children.map(e,(function(e){if(!e||(0,r.isValidElement)(e)&&(a=e.props)&&"object"==typeof a&&"value"in a)return e;var a;throw new Error("Docusaurus error: Bad child <"+("string"==typeof e.type?e.type:e.type.name)+'>: all children of the component should be , and every should have a unique "value" prop.')})))?void 0:t.filter(Boolean))?a:[]}(e).map((function(e){var a=e.props;return{value:a.value,label:a.label,attributes:a.attributes,default:a.default}}))}function p(e){var a=e.values,t=e.children;return(0,r.useMemo)((function(){var e=null!=a?a:d(t);return function(e){var a=(0,u.l)(e,(function(e,a){return e.value===a.value}));if(a.length>0)throw new Error('Docusaurus error: Duplicate values "'+a.map((function(e){return e.value})).join(", ")+'" found in . Every value needs to be unique.')}(e),e}),[a,t])}function m(e){var a=e.value;return e.tabValues.some((function(e){return e.value===a}))}function h(e){var a=e.queryString,t=void 0!==a&&a,n=e.groupId,i=(0,l.k6)(),o=function(e){var a=e.queryString,t=void 0!==a&&a,n=e.groupId;if("string"==typeof t)return t;if(!1===t)return null;if(!0===t&&!n)throw new Error('Docusaurus error: The component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".');return null!=n?n:null}({queryString:t,groupId:n});return[(0,s._X)(o),(0,r.useCallback)((function(e){if(o){var a=new URLSearchParams(i.location.search);a.set(o,e),i.replace(Object.assign({},i.location,{search:a.toString()}))}}),[o,i])]}function k(e){var a,t,n,i,o=e.defaultValue,l=e.queryString,s=void 0!==l&&l,u=e.groupId,d=p(e),k=(0,r.useState)((function(){return function(e){var a,t=e.defaultValue,n=e.tabValues;if(0===n.length)throw new Error("Docusaurus error: the component requires at least one children component");if(t){if(!m({value:t,tabValues:n}))throw new Error('Docusaurus error: The has a defaultValue "'+t+'" but none of its children has the corresponding value. Available values are: '+n.map((function(e){return e.value})).join(", ")+". If you intend to show no default tab, use defaultValue={null} instead.");return t}var r=null!=(a=n.find((function(e){return e.default})))?a:n[0];if(!r)throw new Error("Unexpected error: 0 tabValues");return r.value}({defaultValue:o,tabValues:d})})),f=k[0],v=k[1],y=h({queryString:s,groupId:u}),g=y[0],N=y[1],b=(a=function(e){return e?"docusaurus.tab."+e:null}({groupId:u}.groupId),t=(0,c.Nk)(a),n=t[0],i=t[1],[n,(0,r.useCallback)((function(e){a&&i.set(e)}),[a,i])]),C=b[0],x=b[1],E=function(){var e=null!=g?g:C;return m({value:e,tabValues:d})?e:null}();return(0,r.useLayoutEffect)((function(){E&&v(E)}),[E]),{selectedValue:f,selectValue:(0,r.useCallback)((function(e){if(!m({value:e,tabValues:d}))throw new Error("Can't select invalid tab value="+e);v(e),N(e),x(e)}),[N,x,d]),tabValues:d}}var f=t(6457);const v="tabList_J5MA",y="tabItem_l0OV";function g(e){var a=e.className,t=e.block,l=e.selectedValue,s=e.selectValue,u=e.tabValues,c=[],d=(0,o.o5)().blockElementScrollPositionUntilNextRender,p=function(e){var a=e.currentTarget,t=c.indexOf(a),n=u[t].value;n!==l&&(d(a),s(n))},m=function(e){var a,t=null;switch(e.key){case"Enter":p(e);break;case"ArrowRight":var n,r=c.indexOf(e.currentTarget)+1;t=null!=(n=c[r])?n:c[0];break;case"ArrowLeft":var i,o=c.indexOf(e.currentTarget)-1;t=null!=(i=c[o])?i:c[c.length-1]}null==(a=t)||a.focus()};return r.createElement("ul",{role:"tablist","aria-orientation":"horizontal",className:(0,i.Z)("tabs",{"tabs--block":t},a)},u.map((function(e){var a=e.value,t=e.label,o=e.attributes;return r.createElement("li",(0,n.Z)({role:"tab",tabIndex:l===a?0:-1,"aria-selected":l===a,key:a,ref:function(e){return c.push(e)},onKeyDown:m,onClick:p},o,{className:(0,i.Z)("tabs__item",y,null==o?void 0:o.className,{"tabs__item--active":l===a})}),null!=t?t:a)})))}function N(e){var a=e.lazy,t=e.children,n=e.selectedValue,i=(Array.isArray(t)?t:[t]).filter(Boolean);if(a){var o=i.find((function(e){return e.props.value===n}));return o?(0,r.cloneElement)(o,{className:"margin-top--md"}):null}return r.createElement("div",{className:"margin-top--md"},i.map((function(e,a){return(0,r.cloneElement)(e,{key:a,hidden:e.props.value!==n})})))}function b(e){var a=k(e);return r.createElement("div",{className:(0,i.Z)("tabs-container",v)},r.createElement(g,(0,n.Z)({},e,a)),r.createElement(N,(0,n.Z)({},e,a)))}function C(e){var a=(0,f.Z)();return r.createElement(b,(0,n.Z)({key:String(a)},e))}},546:(e,a,t)=>{t.r(a),t.d(a,{assets:()=>p,contentTitle:()=>c,default:()=>k,frontMatter:()=>u,metadata:()=>d,toc:()=>m});var n=t(5773),r=t(808),i=(t(7378),t(5318)),o=t(3930),l=t(9798),s=["components"],u={title:"ExpressValidator"},c="ExpressValidator",d={unversionedId:"api/express-validator",id:"api/express-validator",title:"ExpressValidator",description:"ExpressValidator",source:"@site/../docs/api/express-validator.md",sourceDirName:"api",slug:"/api/express-validator",permalink:"/docs/next/api/express-validator",draft:!1,editUrl:"https://github.com/express-validator/express-validator/edit/master/docs/../docs/api/express-validator.md",tags:[],version:"current",frontMatter:{title:"ExpressValidator"},sidebar:"api",previous:{title:"ValidationChain",permalink:"/docs/next/api/validation-chain"},next:{title:"matchedData",permalink:"/docs/next/api/matched-data"}},p={},m=[{value:"ExpressValidator",id:"expressvalidator",level:2},{value:"Usage",id:"usage",level:3},{value:"With custom validators only",id:"with-custom-validators-only",level:4},{value:"With custom sanitizers only",id:"with-custom-sanitizers-only",level:4},{value:".check()",id:"check",level:3},{value:".body()",id:"body",level:3},{value:".cookie()",id:"cookie",level:3},{value:".header()",id:"header",level:3},{value:".param()",id:"param",level:3},{value:".query()",id:"query",level:3},{value:".buildCheckFunction()",id:"buildcheckfunction",level:3},{value:".checkExact()",id:"checkexact",level:3},{value:".checkSchema()",id:"checkschema",level:3},{value:".matchedData()",id:"matcheddata",level:3},{value:".oneOf()",id:"oneof",level:3},{value:".validationResult()",id:"validationresult",level:3},{value:"CustomSchema",id:"customschema",level:2},{value:"CustomValidationChain",id:"customvalidationchain",level:2}],h={toc:m};function k(e){var a=e.components,t=(0,r.Z)(e,s);return(0,i.kt)("wrapper",(0,n.Z)({},h,t,{components:a,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"expressvalidator"},(0,i.kt)("inlineCode",{parentName:"h1"},"ExpressValidator")),(0,i.kt)("h2",{id:"expressvalidator"},(0,i.kt)("inlineCode",{parentName:"h2"},"ExpressValidator")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator } from 'express-validator';\nnew ExpressValidator(\n customValidators?: Record,\n customSanitizers?: Record,\n options?: {\n errorFormatter: ErrorFormatter;\n }\n);\n")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," is a class which wraps the entire express-validator API, with some differences:"),(0,i.kt)("ol",null,(0,i.kt)("li",{parentName:"ol"},"you can specify custom validators and/or custom sanitizers that are always available in validation chains;"),(0,i.kt)("li",{parentName:"ol"},"you can specify options that apply by default to some functions.")),(0,i.kt)("p",null,(0,i.kt)("inlineCode",{parentName:"p"},"customValidators")," and ",(0,i.kt)("inlineCode",{parentName:"p"},"customSanitizers")," are objects from custom validator/sanitizer name to implementation.",(0,i.kt)("br",null),"\nSee examples in the ",(0,i.kt)("a",{parentName:"p",href:"#usage"},"usage section"),", and see the ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/guides/customizing#custom-validators-and-sanitizers"},'"Custom Validators and Sanitizers" guide'),"\nto learn more."),(0,i.kt)("p",null,"If ",(0,i.kt)("inlineCode",{parentName:"p"},"options.errorFormatter")," is set, it's used as the default error formatter used by ",(0,i.kt)("a",{parentName:"p",href:"#validationresult"},(0,i.kt)("inlineCode",{parentName:"a"},".validationResult()")),"."),(0,i.kt)("h3",{id:"usage"},"Usage"),(0,i.kt)("h4",{id:"with-custom-validators-only"},"With custom validators only"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { body } = new ExpressValidator({\n isEmailNotInUse: async value => {\n const user = await Users.findByEmail(value);\n if (user) {\n throw new Error('E-mail already in use');\n }\n },\n});\n\napp.post('/signup', body('email').isEmailNotInUse(), (req, res) => {});\n")),(0,i.kt)("h4",{id:"with-custom-sanitizers-only"},"With custom sanitizers only"),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { body } = new ExpressValidator({}, {\n muteOffensiveWords: async value => {\n for (const word of offensiveWords) {\n value = value.replaceAll(new RegExp(`\\\\b${word}\\\\b`), word[0].padEnd(word.length, '*'));\n }\n return value;\n },\n});\n\napp.post('/add-comment', body('comment').muteOffensiveWords(), (req, res) => {});\n")),(0,i.kt)("h3",{id:"check"},(0,i.kt)("inlineCode",{parentName:"h3"},".check()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"check(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#check"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"check()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"body"},(0,i.kt)("inlineCode",{parentName:"h3"},".body()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"body(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#body"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"body()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"cookie"},(0,i.kt)("inlineCode",{parentName:"h3"},".cookie()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"cookie(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#cookie"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"cookie()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"header"},(0,i.kt)("inlineCode",{parentName:"h3"},".header()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"header(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#header"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"header()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"param"},(0,i.kt)("inlineCode",{parentName:"h3"},".param()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"param(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#param"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"param()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"query"},(0,i.kt)("inlineCode",{parentName:"h3"},".query()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"query(fields?: string | string[], message?: any): CustomValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check#query"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"query()")," function"),", but returning a\n",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"))," for that ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("h3",{id:"buildcheckfunction"},(0,i.kt)("inlineCode",{parentName:"h3"},".buildCheckFunction()")),(0,i.kt)("h3",{id:"checkexact"},(0,i.kt)("inlineCode",{parentName:"h3"},".checkExact()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check-exact#checkexact"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"checkExact()")," function"),".\nOnly present in ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," for convenience."),(0,i.kt)("h3",{id:"checkschema"},(0,i.kt)("inlineCode",{parentName:"h3"},".checkSchema()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"checkSchema(schema: CustomSchema, defaultLocations?: Location[]): CustomValidationChain[]\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/check-schema#checkschema"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"checkSchema()")," function"),", but the schema can reference\nthe custom validators or sanitizers from the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"const { checkSchema } = new ExpressValidator({ isEmailNotInUse });\napp.post(\n '/signup',\n checkSchema({\n email: { isEmailNotInUse: true },\n }),\n (req, res) => {\n // handle request\n },\n);\n")),(0,i.kt)("h3",{id:"matcheddata"},(0,i.kt)("inlineCode",{parentName:"h3"},".matchedData()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/matched-data"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"matchedData()")," function"),".\nOnly present in ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," for convenience."),(0,i.kt)("h3",{id:"oneof"},(0,i.kt)("inlineCode",{parentName:"h3"},".oneOf()")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/one-of"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"oneOf()")," function"),", but accepts ",(0,i.kt)("a",{parentName:"p",href:"#customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"a"},"CustomValidationChain"),"s"),"\ncreated from ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("h3",{id:"validationresult"},(0,i.kt)("inlineCode",{parentName:"h3"},".validationResult()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"validationResult(req): Result\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/validation-result#validationresult"},"standalone ",(0,i.kt)("inlineCode",{parentName:"a"},"validationResult()")," function"),",\nbut uses the ",(0,i.kt)("inlineCode",{parentName:"p"},"options.errorFormatter")," passed in the constructor by default."),(0,i.kt)(o.Z,{groupId:"lang",mdxType:"Tabs"},(0,i.kt)(l.Z,{value:"js",label:"JavaScript",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-js"},"const { ExpressValidator } = require('express-validator');\n\nconst { query, validationResult } = new ExpressValidator({}, {}, {\n errorFormatter: error => error.msg,\n};\n\napp.post('/hello', query('person').notEmpty(), (req, res) => {\n const result = validationResult(req);\n const errors = result.array();\n // => ['Invalid value', ... ]\n\n const result2 = result.formatWith(error => `${error.msg}!!!`);\n const errors2 = result2.array();\n // => ['Invalid value!!!']\n});\n"))),(0,i.kt)(l.Z,{value:"ts",label:"TypeScript",mdxType:"TabItem"},(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { Result, ExpressValidator } from 'express-validator';\n\nconst { query, validationResult } = new ExpressValidator({}, {}, {\n errorFormatter: error => error.msg as string,\n};\n\napp.post('/hello', query('person').notEmpty(), (req, res) => {\n const result: Result = validationResult(req);\n const errors = result.array();\n // => ['Invalid value', ... ]\n\n const result2: Result = result.formatWith(error => `${error.msg}!!!`);\n const errors2 = result2.array();\n // => ['Invalid value!!!']\n});\n")))),(0,i.kt)("h2",{id:"customschema"},(0,i.kt)("inlineCode",{parentName:"h2"},"CustomSchema")),(0,i.kt)("p",null,"The type of a schema created through ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("p",null,"Has a single generic parameter ",(0,i.kt)("inlineCode",{parentName:"p"},"T"),", which is the type of the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator, CustomSchema } from 'express-validator';\n\nconst myExpressValidator = new ExpressValidator({ isEmailNotInUse });\ntype MyCustomSchema = CustomSchema;\n\nconst schema: MyCustomSchema = {\n email: { isEmailNotInUse: true },\n};\n")),(0,i.kt)("h2",{id:"customvalidationchain"},(0,i.kt)("inlineCode",{parentName:"h2"},"CustomValidationChain")),(0,i.kt)("p",null,"The type of a validation chain created through ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator"),"."),(0,i.kt)("p",null,"Has a single generic parameter ",(0,i.kt)("inlineCode",{parentName:"p"},"T"),", which is the type of the ",(0,i.kt)("inlineCode",{parentName:"p"},"ExpressValidator")," instance."),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { ExpressValidator, CustomValidationChain } from 'express-validator';\n\nconst myExpressValidator = new ExpressValidator({ isEmailNotInUse });\ntype MyValidationChain = CustomValidationChain;\n\nconst chain: MyValidationChain = myExpressValidator.body('email').isEmailNotInUse();\n")))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/60e2c3e9.e99e4a3b.js b/assets/js/60e2c3e9.e99e4a3b.js new file mode 100644 index 0000000..7ba73be --- /dev/null +++ b/assets/js/60e2c3e9.e99e4a3b.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9245],{5318:(e,t,a)=>{a.d(t,{Zo:()=>s,kt:()=>u});var n=a(7378);function r(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function i(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,n)}return a}function o(e){for(var t=1;t=0||(r[a]=e[a]);return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,a)&&(r[a]=e[a])}return r}var c=n.createContext({}),p=function(e){var t=n.useContext(c),a=t;return e&&(a="function"==typeof e?e(t):o(o({},t),e)),a},s=function(e){var t=p(e.components);return n.createElement(c.Provider,{value:t},e.children)},d="mdxType",m={inlineCode:"code",wrapper:function(e){var t=e.children;return n.createElement(n.Fragment,{},t)}},k=n.forwardRef((function(e,t){var a=e.components,r=e.mdxType,i=e.originalType,c=e.parentName,s=l(e,["components","mdxType","originalType","parentName"]),d=p(a),k=r,u=d["".concat(c,".").concat(k)]||d[k]||m[k]||i;return a?n.createElement(u,o(o({ref:t},s),{},{components:a})):n.createElement(u,o({ref:t},s))}));function u(e,t){var a=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var i=a.length,o=new Array(i);o[0]=k;var l={};for(var c in t)hasOwnProperty.call(t,c)&&(l[c]=t[c]);l.originalType=e,l[d]="string"==typeof e?e:r,o[1]=l;for(var p=2;p{a.r(t),a.d(t,{assets:()=>s,contentTitle:()=>c,default:()=>k,frontMatter:()=>l,metadata:()=>p,toc:()=>d});var n=a(5773),r=a(808),i=(a(7378),a(5318)),o=["components"],l={title:"check"},c=void 0,p={unversionedId:"api/check",id:"api/check",title:"check",description:"The check() function is the main API used for validating and sanitizing HTTP requests with express-validator.",source:"@site/../docs/api/check.md",sourceDirName:"api",slug:"/api/check",permalink:"/docs/next/api/check",draft:!1,editUrl:"https://github.com/express-validator/express-validator/edit/master/docs/../docs/api/check.md",tags:[],version:"current",frontMatter:{title:"check"},sidebar:"api",next:{title:"checkExact",permalink:"/docs/next/api/check-exact"}},s={},d=[{value:"check()",id:"check",level:2},{value:"body()",id:"body",level:2},{value:"cookie()",id:"cookie",level:2},{value:"header()",id:"header",level:2},{value:"param()",id:"param",level:2},{value:"query()",id:"query",level:2}],m={toc:d};function k(e){var t=e.components,a=(0,r.Z)(e,o);return(0,i.kt)("wrapper",(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"check()")," function is the main API used for validating and sanitizing HTTP requests with express-validator.\nIt gives you access to all of the built-in validators, sanitizers, and a bunch of other utility\nfunctions to shape the validation just the way you need."),(0,i.kt)("h2",{id:"check"},(0,i.kt)("inlineCode",{parentName:"h2"},"check()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { check } from 'express-validator';\ncheck(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"Parameters:")),(0,i.kt)("table",null,(0,i.kt)("thead",{parentName:"table"},(0,i.kt)("tr",{parentName:"thead"},(0,i.kt)("th",{parentName:"tr",align:null},"Name"),(0,i.kt)("th",{parentName:"tr",align:null},"Description"))),(0,i.kt)("tbody",{parentName:"table"},(0,i.kt)("tr",{parentName:"tbody"},(0,i.kt)("td",{parentName:"tr",align:null},(0,i.kt)("inlineCode",{parentName:"td"},"fields")),(0,i.kt)("td",{parentName:"tr",align:null},"One or more field names to select. If omitted, selects the ",(0,i.kt)("a",{parentName:"td",href:"/docs/next/guides/field-selection#whole-body-selection"},"whole request location"),".")),(0,i.kt)("tr",{parentName:"tbody"},(0,i.kt)("td",{parentName:"tr",align:null},(0,i.kt)("inlineCode",{parentName:"td"},"message")),(0,i.kt)("td",{parentName:"tr",align:null},"Which error message to use when a validator doesn't specify one.")))),(0,i.kt)("p",null,"Creates a ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/validation-chain"},"validation chain")," for one or more fields.\nFields are selected from any of the following request locations:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.body")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.cookies")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.headers")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.query")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.params"))),(0,i.kt)("p",null,"If any of the fields is present in more than one location, then all instances of that field value\nare processed by the validation chain."),(0,i.kt)("h2",{id:"body"},(0,i.kt)("inlineCode",{parentName:"h2"},"body()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { body } from 'express-validator';\nbody(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.body"),"."),(0,i.kt)("h2",{id:"cookie"},(0,i.kt)("inlineCode",{parentName:"h2"},"cookie()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { cookie } from 'express-validator';\ncookie(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.cookies"),"."),(0,i.kt)("h2",{id:"header"},(0,i.kt)("inlineCode",{parentName:"h2"},"header()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { header } from 'express-validator';\nheader(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.headers"),"."),(0,i.kt)("h2",{id:"param"},(0,i.kt)("inlineCode",{parentName:"h2"},"param()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { param } from 'express-validator';\nparam(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#params"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.params"),"."),(0,i.kt)("h2",{id:"query"},(0,i.kt)("inlineCode",{parentName:"h2"},"query()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { query } from 'express-validator';\nquery(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.query"),"."))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/60e2c3e9.eaaa856f.js b/assets/js/60e2c3e9.eaaa856f.js deleted file mode 100644 index 7ef4a47..0000000 --- a/assets/js/60e2c3e9.eaaa856f.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[9245],{5318:(e,t,a)=>{a.d(t,{Zo:()=>p,kt:()=>u});var n=a(7378);function r(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function i(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,n)}return a}function o(e){for(var t=1;t=0||(r[a]=e[a]);return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,a)&&(r[a]=e[a])}return r}var s=n.createContext({}),c=function(e){var t=n.useContext(s),a=t;return e&&(a="function"==typeof e?e(t):o(o({},t),e)),a},p=function(e){var t=c(e.components);return n.createElement(s.Provider,{value:t},e.children)},d="mdxType",m={inlineCode:"code",wrapper:function(e){var t=e.children;return n.createElement(n.Fragment,{},t)}},k=n.forwardRef((function(e,t){var a=e.components,r=e.mdxType,i=e.originalType,s=e.parentName,p=l(e,["components","mdxType","originalType","parentName"]),d=c(a),k=r,u=d["".concat(s,".").concat(k)]||d[k]||m[k]||i;return a?n.createElement(u,o(o({ref:t},p),{},{components:a})):n.createElement(u,o({ref:t},p))}));function u(e,t){var a=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var i=a.length,o=new Array(i);o[0]=k;var l={};for(var s in t)hasOwnProperty.call(t,s)&&(l[s]=t[s]);l.originalType=e,l[d]="string"==typeof e?e:r,o[1]=l;for(var c=2;c{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>k,frontMatter:()=>l,metadata:()=>c,toc:()=>d});var n=a(5773),r=a(808),i=(a(7378),a(5318)),o=["components"],l={title:"check"},s=void 0,c={unversionedId:"api/check",id:"api/check",title:"check",description:"The check() function is the main API used for validating and sanitizing HTTP requests with express-validator.",source:"@site/../docs/api/check.md",sourceDirName:"api",slug:"/api/check",permalink:"/docs/next/api/check",draft:!1,editUrl:"https://github.com/express-validator/express-validator/edit/master/docs/../docs/api/check.md",tags:[],version:"current",frontMatter:{title:"check"},sidebar:"api",next:{title:"checkExact",permalink:"/docs/next/api/check-exact"}},p={},d=[{value:"check()",id:"check",level:2},{value:"body()",id:"body",level:2},{value:"cookies()",id:"cookies",level:2},{value:"headers()",id:"headers",level:2},{value:"params()",id:"params",level:2},{value:"query()",id:"query",level:2}],m={toc:d};function k(e){var t=e.components,a=(0,r.Z)(e,o);return(0,i.kt)("wrapper",(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"check()")," function is the main API used for validating and sanitizing HTTP requests with express-validator.\nIt gives you access to all of the built-in validators, sanitizers, and a bunch of other utility\nfunctions to shape the validation just the way you need."),(0,i.kt)("h2",{id:"check"},(0,i.kt)("inlineCode",{parentName:"h2"},"check()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { check } from 'express-validator';\ncheck(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"Parameters:")),(0,i.kt)("table",null,(0,i.kt)("thead",{parentName:"table"},(0,i.kt)("tr",{parentName:"thead"},(0,i.kt)("th",{parentName:"tr",align:null},"Name"),(0,i.kt)("th",{parentName:"tr",align:null},"Description"))),(0,i.kt)("tbody",{parentName:"table"},(0,i.kt)("tr",{parentName:"tbody"},(0,i.kt)("td",{parentName:"tr",align:null},(0,i.kt)("inlineCode",{parentName:"td"},"fields")),(0,i.kt)("td",{parentName:"tr",align:null},"One or more field names to select. If omitted, selects the ",(0,i.kt)("a",{parentName:"td",href:"/docs/next/guides/field-selection#whole-body-selection"},"whole request location"),".")),(0,i.kt)("tr",{parentName:"tbody"},(0,i.kt)("td",{parentName:"tr",align:null},(0,i.kt)("inlineCode",{parentName:"td"},"message")),(0,i.kt)("td",{parentName:"tr",align:null},"Which error message to use when a validator doesn't specify one.")))),(0,i.kt)("p",null,"Creates a ",(0,i.kt)("a",{parentName:"p",href:"/docs/next/api/validation-chain"},"validation chain")," for one or more fields.\nFields are selected from any of the following request locations:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.body")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.cookies")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.headers")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.query")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.params"))),(0,i.kt)("p",null,"If any of the fields is present in more than one location, then all instances of that field value\nare processed by the validation chain."),(0,i.kt)("h2",{id:"body"},(0,i.kt)("inlineCode",{parentName:"h2"},"body()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { body } from 'express-validator';\nbody(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.body"),"."),(0,i.kt)("h2",{id:"cookies"},(0,i.kt)("inlineCode",{parentName:"h2"},"cookies()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { cookies } from 'express-validator';\ncookies(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.cookies"),"."),(0,i.kt)("h2",{id:"headers"},(0,i.kt)("inlineCode",{parentName:"h2"},"headers()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { headers } from 'express-validator';\nheaders(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.headers"),"."),(0,i.kt)("h2",{id:"params"},(0,i.kt)("inlineCode",{parentName:"h2"},"params()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { params } from 'express-validator';\nparams(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#params"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.params"),"."),(0,i.kt)("h2",{id:"query"},(0,i.kt)("inlineCode",{parentName:"h2"},"query()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { query } from 'express-validator';\nquery(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.query"),"."))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/84854274.24286938.js b/assets/js/84854274.24286938.js deleted file mode 100644 index a529e74..0000000 --- a/assets/js/84854274.24286938.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7455],{5318:(e,t,a)=>{a.d(t,{Zo:()=>p,kt:()=>u});var n=a(7378);function r(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function i(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,n)}return a}function o(e){for(var t=1;t=0||(r[a]=e[a]);return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,a)&&(r[a]=e[a])}return r}var s=n.createContext({}),c=function(e){var t=n.useContext(s),a=t;return e&&(a="function"==typeof e?e(t):o(o({},t),e)),a},p=function(e){var t=c(e.components);return n.createElement(s.Provider,{value:t},e.children)},d="mdxType",m={inlineCode:"code",wrapper:function(e){var t=e.children;return n.createElement(n.Fragment,{},t)}},k=n.forwardRef((function(e,t){var a=e.components,r=e.mdxType,i=e.originalType,s=e.parentName,p=l(e,["components","mdxType","originalType","parentName"]),d=c(a),k=r,u=d["".concat(s,".").concat(k)]||d[k]||m[k]||i;return a?n.createElement(u,o(o({ref:t},p),{},{components:a})):n.createElement(u,o({ref:t},p))}));function u(e,t){var a=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var i=a.length,o=new Array(i);o[0]=k;var l={};for(var s in t)hasOwnProperty.call(t,s)&&(l[s]=t[s]);l.originalType=e,l[d]="string"==typeof e?e:r,o[1]=l;for(var c=2;c{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>s,default:()=>k,frontMatter:()=>l,metadata:()=>c,toc:()=>d});var n=a(5773),r=a(808),i=(a(7378),a(5318)),o=["components"],l={title:"check"},s=void 0,c={unversionedId:"api/check",id:"version-7.0.0/api/check",title:"check",description:"The check() function is the main API used for validating and sanitizing HTTP requests with express-validator.",source:"@site/versioned_docs/version-7.0.0/api/check.md",sourceDirName:"api",slug:"/api/check",permalink:"/docs/api/check",draft:!1,editUrl:"https://github.com/express-validator/express-validator/edit/master/docs/versioned_docs/version-7.0.0/api/check.md",tags:[],version:"7.0.0",frontMatter:{title:"check"},sidebar:"api",next:{title:"checkExact",permalink:"/docs/api/check-exact"}},p={},d=[{value:"check()",id:"check",level:2},{value:"body()",id:"body",level:2},{value:"cookies()",id:"cookies",level:2},{value:"headers()",id:"headers",level:2},{value:"params()",id:"params",level:2},{value:"query()",id:"query",level:2}],m={toc:d};function k(e){var t=e.components,a=(0,r.Z)(e,o);return(0,i.kt)("wrapper",(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"check()")," function is the main API used for validating and sanitizing HTTP requests with express-validator.\nIt gives you access to all of the built-in validators, sanitizers, and a bunch of other utility\nfunctions to shape the validation just the way you need."),(0,i.kt)("h2",{id:"check"},(0,i.kt)("inlineCode",{parentName:"h2"},"check()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { check } from 'express-validator';\ncheck(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"Parameters:")),(0,i.kt)("table",null,(0,i.kt)("thead",{parentName:"table"},(0,i.kt)("tr",{parentName:"thead"},(0,i.kt)("th",{parentName:"tr",align:null},"Name"),(0,i.kt)("th",{parentName:"tr",align:null},"Description"))),(0,i.kt)("tbody",{parentName:"table"},(0,i.kt)("tr",{parentName:"tbody"},(0,i.kt)("td",{parentName:"tr",align:null},(0,i.kt)("inlineCode",{parentName:"td"},"fields")),(0,i.kt)("td",{parentName:"tr",align:null},"One or more field names to select. If omitted, selects the ",(0,i.kt)("a",{parentName:"td",href:"/docs/guides/field-selection#whole-body-selection"},"whole request location"),".")),(0,i.kt)("tr",{parentName:"tbody"},(0,i.kt)("td",{parentName:"tr",align:null},(0,i.kt)("inlineCode",{parentName:"td"},"message")),(0,i.kt)("td",{parentName:"tr",align:null},"Which error message to use when a validator doesn't specify one.")))),(0,i.kt)("p",null,"Creates a ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/validation-chain"},"validation chain")," for one or more fields.\nFields are selected from any of the following request locations:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.body")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.cookies")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.headers")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.query")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.params"))),(0,i.kt)("p",null,"If any of the fields is present in more than one location, then all instances of that field value\nare processed by the validation chain."),(0,i.kt)("h2",{id:"body"},(0,i.kt)("inlineCode",{parentName:"h2"},"body()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { body } from 'express-validator';\nbody(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.body"),"."),(0,i.kt)("h2",{id:"cookies"},(0,i.kt)("inlineCode",{parentName:"h2"},"cookies()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { cookies } from 'express-validator';\ncookies(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.cookies"),"."),(0,i.kt)("h2",{id:"headers"},(0,i.kt)("inlineCode",{parentName:"h2"},"headers()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { headers } from 'express-validator';\nheaders(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.headers"),"."),(0,i.kt)("h2",{id:"params"},(0,i.kt)("inlineCode",{parentName:"h2"},"params()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { params } from 'express-validator';\nparams(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#params"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.params"),"."),(0,i.kt)("h2",{id:"query"},(0,i.kt)("inlineCode",{parentName:"h2"},"query()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { query } from 'express-validator';\nquery(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.query"),"."))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/84854274.82275863.js b/assets/js/84854274.82275863.js new file mode 100644 index 0000000..2d775c6 --- /dev/null +++ b/assets/js/84854274.82275863.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[7455],{5318:(e,t,a)=>{a.d(t,{Zo:()=>p,kt:()=>u});var n=a(7378);function r(e,t,a){return t in e?Object.defineProperty(e,t,{value:a,enumerable:!0,configurable:!0,writable:!0}):e[t]=a,e}function i(e,t){var a=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),a.push.apply(a,n)}return a}function o(e){for(var t=1;t=0||(r[a]=e[a]);return r}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,a)&&(r[a]=e[a])}return r}var c=n.createContext({}),s=function(e){var t=n.useContext(c),a=t;return e&&(a="function"==typeof e?e(t):o(o({},t),e)),a},p=function(e){var t=s(e.components);return n.createElement(c.Provider,{value:t},e.children)},d="mdxType",m={inlineCode:"code",wrapper:function(e){var t=e.children;return n.createElement(n.Fragment,{},t)}},k=n.forwardRef((function(e,t){var a=e.components,r=e.mdxType,i=e.originalType,c=e.parentName,p=l(e,["components","mdxType","originalType","parentName"]),d=s(a),k=r,u=d["".concat(c,".").concat(k)]||d[k]||m[k]||i;return a?n.createElement(u,o(o({ref:t},p),{},{components:a})):n.createElement(u,o({ref:t},p))}));function u(e,t){var a=arguments,r=t&&t.mdxType;if("string"==typeof e||r){var i=a.length,o=new Array(i);o[0]=k;var l={};for(var c in t)hasOwnProperty.call(t,c)&&(l[c]=t[c]);l.originalType=e,l[d]="string"==typeof e?e:r,o[1]=l;for(var s=2;s{a.r(t),a.d(t,{assets:()=>p,contentTitle:()=>c,default:()=>k,frontMatter:()=>l,metadata:()=>s,toc:()=>d});var n=a(5773),r=a(808),i=(a(7378),a(5318)),o=["components"],l={title:"check"},c=void 0,s={unversionedId:"api/check",id:"version-7.0.0/api/check",title:"check",description:"The check() function is the main API used for validating and sanitizing HTTP requests with express-validator.",source:"@site/versioned_docs/version-7.0.0/api/check.md",sourceDirName:"api",slug:"/api/check",permalink:"/docs/api/check",draft:!1,editUrl:"https://github.com/express-validator/express-validator/edit/master/docs/versioned_docs/version-7.0.0/api/check.md",tags:[],version:"7.0.0",frontMatter:{title:"check"},sidebar:"api",next:{title:"checkExact",permalink:"/docs/api/check-exact"}},p={},d=[{value:"check()",id:"check",level:2},{value:"body()",id:"body",level:2},{value:"cookie()",id:"cookie",level:2},{value:"header()",id:"header",level:2},{value:"param()",id:"param",level:2},{value:"query()",id:"query",level:2}],m={toc:d};function k(e){var t=e.components,a=(0,r.Z)(e,o);return(0,i.kt)("wrapper",(0,n.Z)({},m,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("p",null,"The ",(0,i.kt)("inlineCode",{parentName:"p"},"check()")," function is the main API used for validating and sanitizing HTTP requests with express-validator.\nIt gives you access to all of the built-in validators, sanitizers, and a bunch of other utility\nfunctions to shape the validation just the way you need."),(0,i.kt)("h2",{id:"check"},(0,i.kt)("inlineCode",{parentName:"h2"},"check()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { check } from 'express-validator';\ncheck(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,(0,i.kt)("strong",{parentName:"p"},"Parameters:")),(0,i.kt)("table",null,(0,i.kt)("thead",{parentName:"table"},(0,i.kt)("tr",{parentName:"thead"},(0,i.kt)("th",{parentName:"tr",align:null},"Name"),(0,i.kt)("th",{parentName:"tr",align:null},"Description"))),(0,i.kt)("tbody",{parentName:"table"},(0,i.kt)("tr",{parentName:"tbody"},(0,i.kt)("td",{parentName:"tr",align:null},(0,i.kt)("inlineCode",{parentName:"td"},"fields")),(0,i.kt)("td",{parentName:"tr",align:null},"One or more field names to select. If omitted, selects the ",(0,i.kt)("a",{parentName:"td",href:"/docs/guides/field-selection#whole-body-selection"},"whole request location"),".")),(0,i.kt)("tr",{parentName:"tbody"},(0,i.kt)("td",{parentName:"tr",align:null},(0,i.kt)("inlineCode",{parentName:"td"},"message")),(0,i.kt)("td",{parentName:"tr",align:null},"Which error message to use when a validator doesn't specify one.")))),(0,i.kt)("p",null,"Creates a ",(0,i.kt)("a",{parentName:"p",href:"/docs/api/validation-chain"},"validation chain")," for one or more fields.\nFields are selected from any of the following request locations:"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.body")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.cookies")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.headers")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.query")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("inlineCode",{parentName:"li"},"req.params"))),(0,i.kt)("p",null,"If any of the fields is present in more than one location, then all instances of that field value\nare processed by the validation chain."),(0,i.kt)("h2",{id:"body"},(0,i.kt)("inlineCode",{parentName:"h2"},"body()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { body } from 'express-validator';\nbody(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.body"),"."),(0,i.kt)("h2",{id:"cookie"},(0,i.kt)("inlineCode",{parentName:"h2"},"cookie()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { cookie } from 'express-validator';\ncookie(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.cookies"),"."),(0,i.kt)("h2",{id:"header"},(0,i.kt)("inlineCode",{parentName:"h2"},"header()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { header } from 'express-validator';\nheader(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.headers"),"."),(0,i.kt)("h2",{id:"param"},(0,i.kt)("inlineCode",{parentName:"h2"},"param()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { param } from 'express-validator';\nparam(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#params"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.params"),"."),(0,i.kt)("h2",{id:"query"},(0,i.kt)("inlineCode",{parentName:"h2"},"query()")),(0,i.kt)("pre",null,(0,i.kt)("code",{parentName:"pre",className:"language-ts"},"import { query } from 'express-validator';\nquery(fields?: string | string[], message?: any): ValidationChain\n")),(0,i.kt)("p",null,"Same as ",(0,i.kt)("a",{parentName:"p",href:"#check"},(0,i.kt)("inlineCode",{parentName:"a"},"check()")),", but only checking ",(0,i.kt)("inlineCode",{parentName:"p"},"req.query"),"."))}k.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/runtime~main.c46e207b.js b/assets/js/runtime~main.96406a10.js similarity index 98% rename from assets/js/runtime~main.c46e207b.js rename to assets/js/runtime~main.96406a10.js index 702a469..e619982 100644 --- a/assets/js/runtime~main.c46e207b.js +++ b/assets/js/runtime~main.96406a10.js @@ -1 +1 @@ -(()=>{"use strict";var e,a,d,c,f={},b={};function r(e){var a=b[e];if(void 0!==a)return a.exports;var d=b[e]={id:e,loaded:!1,exports:{}};return f[e].call(d.exports,d,d.exports,r),d.loaded=!0,d.exports}r.m=f,r.c=b,e=[],r.O=(a,d,c,f)=>{if(!d){var b=1/0;for(i=0;i=f)&&Object.keys(r.O).every((e=>r.O[e](d[o])))?d.splice(o--,1):(t=!1,f0&&e[i-1][2]>f;i--)e[i]=e[i-1];e[i]=[d,c,f]},r.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return r.d(a,{a:a}),a},d=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,c){if(1&c&&(e=this(e)),8&c)return e;if("object"==typeof e&&e){if(4&c&&e.__esModule)return e;if(16&c&&"function"==typeof e.then)return e}var f=Object.create(null);r.r(f);var b={};a=a||[null,d({}),d([]),d(d)];for(var t=2&c&&e;"object"==typeof t&&!~a.indexOf(t);t=d(t))Object.getOwnPropertyNames(t).forEach((a=>b[a]=()=>e[a]));return b.default=()=>e,r.d(f,b),f},r.d=(e,a)=>{for(var d in a)r.o(a,d)&&!r.o(e,d)&&Object.defineProperty(e,d,{enumerable:!0,get:a[d]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((a,d)=>(r.f[d](e,a),a)),[])),r.u=e=>"assets/js/"+({6:"9b025403",49:"d2466f6f",53:"935f2afb",103:"ea4e3d0a",134:"3f3aaba7",272:"6c584ec9",283:"e3068001",355:"a13d31c2",402:"e90bd361",410:"b5804665",415:"81fa8341",452:"8786b357",496:"09ed2da6",550:"744891a1",573:"8932c20f",576:"f424d1a5",631:"5ef10653",668:"bfdce259",719:"41395dbd",731:"7192b7de",742:"2ac7523a",769:"16ad331b",777:"4fa180b0",785:"cb59c4a0",821:"115cd9a3",823:"dafd2d45",844:"f0db630e",888:"d4b00c8e",936:"58eb6a88",954:"4bd184f6",985:"6c20e6ff",1e3:"f2ed1a45",1042:"8586747a",1049:"b3206f11",1050:"23c664e3",1120:"e16cd061",1185:"f0dd6a1c",1218:"1bcb6c12",1239:"11773138",1290:"2b577994",1321:"313a01e8",1343:"b2ce4c9b",1367:"9cf56202",1400:"bf1edca5",1435:"994031bd",1444:"74feb7e9",1455:"0669159b",1472:"f9670de5",1526:"5375b588",1593:"1289b509",1594:"e576ad5a",1608:"c6c4033b",1642:"807e0e7f",1651:"20f77e87",1658:"af5aa801",1662:"f9d96800",1850:"8210fdb1",1894:"d8146d88",1908:"754a5aa1",1940:"614c5cb3",1981:"52d32b65",2027:"1625e41d",2028:"1b317434",2116:"143fd892",2131:"0bd1d967",2152:"108bd67c",2218:"2b6906c9",2225:"5cd6c63e",2227:"3807d7d6",2252:"bfc3545d",2306:"5239ef28",2308:"94373f1a",2316:"606deeae",2330:"c8ebe515",2365:"ed6862e8",2371:"f6e3ec6f",2400:"b85acdea",2413:"da63d163",2420:"29381d51",2436:"56abd55d",2467:"84527cbe",2474:"e2ce234d",2487:"5192a38d",2496:"b830c51f",2553:"3aff40da",2554:"6a498910",2575:"552c4e0c",2584:"0d5720d7",2625:"f0627f31",2653:"8fa8d26c",2655:"6f6762d6",2657:"18a48af9",2660:"928de919",2685:"f851cefd",2688:"6c93fab4",2771:"a91c4286",2788:"7a39c63d",2796:"4c8950db",2803:"609507dd",2804:"04f4d10e",2810:"3bebfd13",2818:"f9296bce",2886:"fb281095",2924:"a421f136",2935:"99dc5750",3024:"ff72b8c5",3065:"f53fc191",3099:"59394caa",3150:"235a3768",3212:"46df1549",3224:"be187cac",3230:"690d9910",3297:"3cc4a212",3351:"5d391cac",3361:"4c33d3af",3367:"4ff64585",3402:"f2fce86e",3479:"90ebd9bb",3499:"be21ce14",3514:"e7b1c7fb",3535:"787bd795",3539:"49a2de41",3574:"09a3d573",3598:"35be87b0",3624:"3a4485c3",3716:"01b164d8",3815:"6421a520",3916:"a9582fe4",3925:"280ddd3f",4014:"392f1828",4089:"0a830855",4148:"d48f303d",4163:"e00e9744",4199:"6321fd3f",4205:"b5072790",4223:"e8d874da",4295:"d96b90b7",4340:"31f4abdf",4361:"7bb53413",4371:"329a2b2c",4372:"31cac2d3",4387:"9fd49971",4402:"19cdea2a",4404:"97a83304",4415:"45b4adc3",4488:"406269e3",4563:"bb7899cf",4564:"2a2911a0",4567:"81c85956",4585:"c32c8e15",4632:"a8124785",4654:"81d235f1",4673:"fb56a3bd",4679:"a36d4da6",4682:"f85307a1",4727:"df70af35",4728:"acc6ec00",4804:"e601491c",4805:"f0e54ba1",4873:"d9a94183",4894:"25c500d7",4929:"51ec4823",4933:"9667b125",4942:"9e15f089",4998:"8accfa6b",5003:"acfe585e",5149:"81fb6d2e",5160:"dc82b870",5206:"780ab5fe",5211:"ca77dae4",5257:"d30eb9d5",5297:"464acffe",5326:"415d22d3",5393:"7a1f4a4b",5420:"b6abd322",5453:"62637bea",5511:"b605821b",5601:"8b704fbf",5671:"3ba47c53",5719:"f5b0ea4e",5722:"842f7607",5752:"e096712b",5838:"12cd9398",5938:"bf35a50a",5941:"53d239a6",5961:"5a8128fc",5987:"f271fbd1",6002:"9eb21ad8",6003:"1356c1e0",6064:"09b1f4ec",6069:"9daadb77",6129:"c59e05db",6138:"2d780b31",6167:"6ba78147",6199:"49e32276",6252:"1c39fe1c",6296:"1a74ecf5",6302:"3e43c26d",6374:"d3874e59",6391:"5141b302",6397:"de021951",6428:"a13cc575",6460:"f8f2717e",6539:"0a484b7f",6549:"531e34f7",6568:"03a88bad",6571:"56f260e6",6601:"801cd2ac",6603:"ad0d1242",6639:"a75ec5e6",6668:"e40fdf3e",6697:"0a0856d1",6722:"9ad59d1a",6743:"2a1f3a69",6749:"46a1d8da",6760:"97e6230f",6762:"aba198a0",6775:"4f65b59d",6787:"4e289b8c",6824:"8c6e4059",6847:"eefaeb96",6857:"249142be",6971:"7e82ff00",7035:"b3532997",7045:"b0b18499",7073:"32280d2a",7118:"a4c58ea5",7124:"1eba2b69",7181:"61465158",7184:"9efd0bac",7194:"0761ccf0",7226:"bdb71c26",7230:"28cf53e0",7320:"aff97f8f",7351:"80a7c393",7353:"40637d96",7354:"633ab802",7371:"be76f99b",7376:"620c1ecf",7455:"84854274",7466:"a3b3261e",7510:"057e32cd",7548:"e6d95f92",7562:"6336d072",7566:"ed701caf",7593:"a5b875af",7596:"1be1dd71",7603:"bbfb0947",7640:"d7a0e816",7651:"59e4c8ed",7682:"3a190d01",7700:"cb2c64da",7709:"c9607746",7716:"fc25dd3d",7772:"873012db",7786:"cf3e925d",7813:"a9abf8f4",7821:"9d83e1d1",7823:"0e3d8387",7825:"141f29dd",7839:"73da8aa8",7849:"9e212ebb",7857:"02855f38",7895:"5dcb72f3",7897:"4031e9f7",7901:"643d8a8d",7918:"17896441",7920:"1a4e3797",7946:"8f8adbc7",7976:"a278eb8a",7998:"dcc0022e",8115:"1927753e",8128:"dea898c0",8143:"62fe928d",8174:"5485dabc",8179:"a46578cf",8242:"576fbfe0",8245:"35a54963",8360:"d720a69e",8369:"544ce753",8377:"9269c30e",8430:"b8f5ca21",8460:"e4522466",8468:"bec209e4",8520:"39d2b2a1",8551:"e8eb75b8",8562:"a2f4a134",8568:"d7b686af",8576:"3611a290",8626:"1786974b",8635:"10564578",8651:"e7296c31",8669:"daaec077",8671:"83716646",8706:"82b8438d",8707:"85522cfa",8792:"0c9e3a88",8806:"43bc6ea7",8843:"74c840dd",8890:"ec3aa2a7",8909:"5091bfe8",8915:"0ff7615f",8921:"a554bc57",8940:"7b9d511f",8974:"1d64ce3b",9117:"91266340",9124:"cec11939",9166:"2718a84a",9170:"953f1846",9188:"cdfbc197",9200:"1a50ba5c",9245:"60e2c3e9",9252:"32725dec",9265:"91dcd4bd",9351:"c228b49c",9376:"97dbc2fa",9493:"adde0795",9507:"c0f3f8dd",9514:"1be78505",9553:"d8a3c4e8",9601:"5c213362",9609:"b2d3a646",9612:"eb21ac32",9677:"f5707f2d",9681:"f2b9d9a0",9817:"14eb3368",9819:"8bead906",9826:"e6b28b9a",9943:"2d750523",9952:"4d9fef28",9961:"2285ff78",9964:"e819c839"}[e]||e)+"."+{6:"a0809e49",49:"2d2a3a45",53:"cffed61e",103:"6360436d",134:"103641b9",272:"052388cc",283:"5d3cddb4",355:"83a5b992",402:"7cacbae7",410:"37027f65",415:"d22b46f7",452:"197bdf75",496:"f613d5d4",550:"1c06a569",573:"ccc85d41",576:"a19d2041",631:"18cb5a7b",668:"b554ebbc",719:"13b7998a",731:"1d4c9baf",742:"1f7677fe",769:"236aeaaf",777:"b9b640ee",785:"41f7db6d",821:"b4c2a2d9",823:"56cc9b06",844:"bbada611",888:"f3df612a",936:"ec022a34",954:"5b57d984",985:"6f7719bc",1e3:"47a552ed",1042:"5f273b1b",1049:"4761d745",1050:"e69d11df",1120:"ad9e1388",1185:"4fad6916",1218:"fceb2b2d",1239:"f582fce1",1290:"4b25858b",1321:"1541be1d",1343:"bc8720d2",1367:"8f6d2cb8",1400:"9018dfef",1435:"fe57a877",1444:"b327d72b",1455:"803f2bf6",1472:"b96e1fb6",1526:"2d312b7f",1593:"4e2f65a2",1594:"fd2635b1",1608:"8772bfac",1642:"58fd90c2",1651:"b335dc6c",1658:"78907435",1662:"ff7b9072",1850:"4199b587",1894:"544488d4",1908:"fca041e4",1940:"09242807",1981:"23a10be1",2027:"69d4238e",2028:"6fb18cd6",2116:"ca527ced",2131:"d4ec2a3d",2152:"aa370bb3",2218:"d76a1958",2225:"1b3ea5d7",2227:"33d5212d",2252:"4038bfa0",2306:"5b28362d",2308:"b90f861c",2316:"05a55327",2330:"139f1349",2365:"a66d0f4c",2371:"f6b8a2f3",2400:"72298f18",2413:"55471bef",2420:"3e46ebe4",2436:"05996851",2467:"a6938fce",2474:"27584129",2487:"430f9e25",2496:"e16065e3",2553:"3466bb35",2554:"80d285ba",2575:"d0b92952",2584:"fcbaaa52",2625:"bd923c33",2653:"dcc065dc",2655:"7a293757",2657:"6961db7d",2660:"d3845428",2685:"567bbbb5",2688:"e965f644",2771:"7d28ad30",2788:"98f63df4",2796:"2ac46611",2803:"fc0c4e35",2804:"ae2aea36",2810:"1368da01",2818:"4e7c4fbd",2886:"e4c7a40e",2924:"8443a925",2935:"9ba9bf29",3024:"b59c8d69",3065:"7eb2b1dc",3099:"dcedb18a",3150:"2034495f",3212:"1293b474",3224:"811d4d3a",3230:"924fadfa",3297:"cdf3e856",3351:"a7843562",3361:"e7f1e7e2",3367:"0ae9319c",3402:"9a63949e",3479:"ed7c1a24",3499:"f80e3b7c",3514:"afe3fcf8",3535:"c007e7a0",3539:"429d356d",3574:"ef16e307",3598:"28210f59",3624:"cc228b34",3716:"8bbb559a",3815:"ef545eb8",3893:"a73ae4a4",3916:"ed3e5873",3925:"b8dde18d",4014:"58608de7",4089:"d025a522",4148:"982fa3ad",4163:"4a7abcd4",4199:"ef41b2e8",4205:"4135f282",4223:"ef67eb11",4295:"fe21b519",4340:"c86ff17a",4361:"1a9e7e6c",4371:"7ceef633",4372:"5526c807",4387:"86cdb06c",4402:"5dd5e414",4404:"f37875c4",4415:"9b1e4a6e",4488:"000c3810",4563:"4c156130",4564:"847dbc59",4567:"0e3fd2b8",4585:"fc51e049",4632:"ad048b7e",4654:"5cd17655",4670:"7505f65b",4673:"157537d4",4679:"6ea7799c",4682:"927e06e7",4727:"24324739",4728:"9548e83c",4804:"f0bbcc86",4805:"b487dc88",4873:"a4028090",4894:"e5068d91",4929:"bae29a52",4933:"5fecbf67",4942:"997a7776",4998:"64a2f0f1",5003:"24868a24",5149:"1e446259",5160:"e2bc29d4",5206:"8857d8bf",5211:"240d56a8",5257:"0d5d93f5",5297:"6072b626",5326:"c05ba79a",5393:"03799846",5420:"bdb25c6a",5453:"5e5acd1f",5511:"e8ada5dc",5601:"612e5f6f",5671:"a236af23",5719:"c48022f0",5722:"ff473bb1",5752:"73d81066",5838:"572beee5",5938:"24925353",5941:"5f2c9ebe",5961:"4439422b",5987:"8c515fda",6002:"cb5e5945",6003:"f2bb6af3",6064:"38c6f47d",6069:"f5b11f86",6129:"c892cbdc",6138:"cb4bec8c",6167:"b9f2451d",6199:"dac02bbd",6252:"c75a8b9d",6296:"32e047e0",6302:"c858dede",6374:"c10ff622",6391:"64715933",6397:"cf2919d3",6428:"d8b3e1a0",6460:"b67fef84",6539:"4d688384",6549:"7bfa0a02",6568:"c29ece07",6571:"ad423613",6601:"76649944",6603:"a09045cf",6639:"0d88c64a",6668:"ca106e53",6697:"09b90ec2",6722:"610a4dfc",6743:"75668e44",6749:"96c171af",6760:"83cdcc2f",6762:"b4819cf4",6775:"e3893092",6787:"c33a8e6e",6824:"6809fc15",6847:"1ff8550f",6857:"fc1a4755",6971:"eef9a167",7035:"04181932",7045:"6f842660",7073:"5614810e",7118:"bb8cf260",7124:"85699964",7181:"7f811852",7184:"c13466db",7194:"4d561a7d",7226:"e5f89144",7230:"ae10d3cb",7320:"3e1e5511",7351:"f88e1a60",7353:"fc1e18b5",7354:"e320b6f5",7371:"49b6db93",7376:"129738cc",7455:"24286938",7466:"ee217c5e",7510:"5a7b38d8",7548:"5e9064f6",7562:"423dc099",7566:"93a7c99e",7593:"84cd8c35",7596:"c6999d10",7603:"348598d6",7640:"4d7767cc",7651:"1103dc59",7682:"49ac0517",7700:"28126961",7709:"92610cca",7716:"f84b5e75",7772:"7857929a",7786:"1bfcc28d",7813:"c0fb5b58",7821:"85124642",7823:"2033f2c0",7825:"c272b72c",7839:"3cb9aad7",7849:"0876a544",7857:"d047e27b",7895:"68aa0a9b",7897:"55d3e243",7901:"11307c6e",7918:"54dd059c",7920:"c7887816",7946:"b8366875",7976:"02fc1ce7",7998:"f7e6e8e3",8115:"5c0e1035",8128:"b8b74bee",8143:"be0b0fa9",8174:"13168adb",8179:"1ad43b76",8242:"fbbc4aec",8245:"cdd4601b",8360:"de8cdf51",8369:"c94fe608",8377:"035d7d6a",8430:"48156def",8460:"b77ca010",8468:"cbd72add",8520:"88bc633b",8551:"3d0ab95d",8562:"e4da1372",8568:"a15cae71",8576:"9d19d9a9",8626:"e2664616",8635:"ddf80469",8651:"8799e2f5",8669:"1006f8eb",8671:"e5ec4f73",8706:"90b4e0d9",8707:"d47843b9",8777:"2a45b830",8792:"ae3b390e",8806:"084fb41f",8843:"db02c810",8890:"0bfcf124",8909:"a5e21bbd",8915:"6d5489c6",8921:"7a8ad8d6",8940:"7baf1fc1",8974:"f816bfd6",9117:"5f323c3f",9124:"15b46b55",9127:"51d941eb",9166:"ca40ab90",9170:"7ceae35c",9188:"30898979",9200:"6ddcec01",9245:"eaaa856f",9252:"0479c08c",9265:"752d7b48",9351:"19aae2a1",9376:"2a9f630d",9493:"534949ef",9507:"e030864f",9514:"40118b63",9553:"57d90fd5",9601:"aa596d2b",9609:"95f18f5a",9612:"b5eb15ee",9677:"02bd9f4c",9681:"a3d127ee",9817:"6bc6a528",9819:"3783749c",9826:"e6b0577e",9943:"db170a85",9952:"ee9354a8",9961:"bc231ea8",9964:"3b8d47ab"}[e]+".js",r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),c={},r.l=(e,a,d,f)=>{if(c[e])c[e].push(a);else{var b,t;if(void 0!==d)for(var o=document.getElementsByTagName("script"),n=0;n{b.onerror=b.onload=null,clearTimeout(u);var f=c[e];if(delete c[e],b.parentNode&&b.parentNode.removeChild(b),f&&f.forEach((e=>e(d))),a)return a(d)},u=setTimeout(l.bind(null,void 0,{type:"timeout",target:b}),12e4);b.onerror=l.bind(null,b.onerror),b.onload=l.bind(null,b.onload),t&&document.head.appendChild(b)}},r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.p="/",r.gca=function(e){return e={10564578:"8635",11773138:"1239",17896441:"7918",61465158:"7181",83716646:"8671",84854274:"7455",91266340:"9117","9b025403":"6",d2466f6f:"49","935f2afb":"53",ea4e3d0a:"103","3f3aaba7":"134","6c584ec9":"272",e3068001:"283",a13d31c2:"355",e90bd361:"402",b5804665:"410","81fa8341":"415","8786b357":"452","09ed2da6":"496","744891a1":"550","8932c20f":"573",f424d1a5:"576","5ef10653":"631",bfdce259:"668","41395dbd":"719","7192b7de":"731","2ac7523a":"742","16ad331b":"769","4fa180b0":"777",cb59c4a0:"785","115cd9a3":"821",dafd2d45:"823",f0db630e:"844",d4b00c8e:"888","58eb6a88":"936","4bd184f6":"954","6c20e6ff":"985",f2ed1a45:"1000","8586747a":"1042",b3206f11:"1049","23c664e3":"1050",e16cd061:"1120",f0dd6a1c:"1185","1bcb6c12":"1218","2b577994":"1290","313a01e8":"1321",b2ce4c9b:"1343","9cf56202":"1367",bf1edca5:"1400","994031bd":"1435","74feb7e9":"1444","0669159b":"1455",f9670de5:"1472","5375b588":"1526","1289b509":"1593",e576ad5a:"1594",c6c4033b:"1608","807e0e7f":"1642","20f77e87":"1651",af5aa801:"1658",f9d96800:"1662","8210fdb1":"1850",d8146d88:"1894","754a5aa1":"1908","614c5cb3":"1940","52d32b65":"1981","1625e41d":"2027","1b317434":"2028","143fd892":"2116","0bd1d967":"2131","108bd67c":"2152","2b6906c9":"2218","5cd6c63e":"2225","3807d7d6":"2227",bfc3545d:"2252","5239ef28":"2306","94373f1a":"2308","606deeae":"2316",c8ebe515:"2330",ed6862e8:"2365",f6e3ec6f:"2371",b85acdea:"2400",da63d163:"2413","29381d51":"2420","56abd55d":"2436","84527cbe":"2467",e2ce234d:"2474","5192a38d":"2487",b830c51f:"2496","3aff40da":"2553","6a498910":"2554","552c4e0c":"2575","0d5720d7":"2584",f0627f31:"2625","8fa8d26c":"2653","6f6762d6":"2655","18a48af9":"2657","928de919":"2660",f851cefd:"2685","6c93fab4":"2688",a91c4286:"2771","7a39c63d":"2788","4c8950db":"2796","609507dd":"2803","04f4d10e":"2804","3bebfd13":"2810",f9296bce:"2818",fb281095:"2886",a421f136:"2924","99dc5750":"2935",ff72b8c5:"3024",f53fc191:"3065","59394caa":"3099","235a3768":"3150","46df1549":"3212",be187cac:"3224","690d9910":"3230","3cc4a212":"3297","5d391cac":"3351","4c33d3af":"3361","4ff64585":"3367",f2fce86e:"3402","90ebd9bb":"3479",be21ce14:"3499",e7b1c7fb:"3514","787bd795":"3535","49a2de41":"3539","09a3d573":"3574","35be87b0":"3598","3a4485c3":"3624","01b164d8":"3716","6421a520":"3815",a9582fe4:"3916","280ddd3f":"3925","392f1828":"4014","0a830855":"4089",d48f303d:"4148",e00e9744:"4163","6321fd3f":"4199",b5072790:"4205",e8d874da:"4223",d96b90b7:"4295","31f4abdf":"4340","7bb53413":"4361","329a2b2c":"4371","31cac2d3":"4372","9fd49971":"4387","19cdea2a":"4402","97a83304":"4404","45b4adc3":"4415","406269e3":"4488",bb7899cf:"4563","2a2911a0":"4564","81c85956":"4567",c32c8e15:"4585",a8124785:"4632","81d235f1":"4654",fb56a3bd:"4673",a36d4da6:"4679",f85307a1:"4682",df70af35:"4727",acc6ec00:"4728",e601491c:"4804",f0e54ba1:"4805",d9a94183:"4873","25c500d7":"4894","51ec4823":"4929","9667b125":"4933","9e15f089":"4942","8accfa6b":"4998",acfe585e:"5003","81fb6d2e":"5149",dc82b870:"5160","780ab5fe":"5206",ca77dae4:"5211",d30eb9d5:"5257","464acffe":"5297","415d22d3":"5326","7a1f4a4b":"5393",b6abd322:"5420","62637bea":"5453",b605821b:"5511","8b704fbf":"5601","3ba47c53":"5671",f5b0ea4e:"5719","842f7607":"5722",e096712b:"5752","12cd9398":"5838",bf35a50a:"5938","53d239a6":"5941","5a8128fc":"5961",f271fbd1:"5987","9eb21ad8":"6002","1356c1e0":"6003","09b1f4ec":"6064","9daadb77":"6069",c59e05db:"6129","2d780b31":"6138","6ba78147":"6167","49e32276":"6199","1c39fe1c":"6252","1a74ecf5":"6296","3e43c26d":"6302",d3874e59:"6374","5141b302":"6391",de021951:"6397",a13cc575:"6428",f8f2717e:"6460","0a484b7f":"6539","531e34f7":"6549","03a88bad":"6568","56f260e6":"6571","801cd2ac":"6601",ad0d1242:"6603",a75ec5e6:"6639",e40fdf3e:"6668","0a0856d1":"6697","9ad59d1a":"6722","2a1f3a69":"6743","46a1d8da":"6749","97e6230f":"6760",aba198a0:"6762","4f65b59d":"6775","4e289b8c":"6787","8c6e4059":"6824",eefaeb96:"6847","249142be":"6857","7e82ff00":"6971",b3532997:"7035",b0b18499:"7045","32280d2a":"7073",a4c58ea5:"7118","1eba2b69":"7124","9efd0bac":"7184","0761ccf0":"7194",bdb71c26:"7226","28cf53e0":"7230",aff97f8f:"7320","80a7c393":"7351","40637d96":"7353","633ab802":"7354",be76f99b:"7371","620c1ecf":"7376",a3b3261e:"7466","057e32cd":"7510",e6d95f92:"7548","6336d072":"7562",ed701caf:"7566",a5b875af:"7593","1be1dd71":"7596",bbfb0947:"7603",d7a0e816:"7640","59e4c8ed":"7651","3a190d01":"7682",cb2c64da:"7700",c9607746:"7709",fc25dd3d:"7716","873012db":"7772",cf3e925d:"7786",a9abf8f4:"7813","9d83e1d1":"7821","0e3d8387":"7823","141f29dd":"7825","73da8aa8":"7839","9e212ebb":"7849","02855f38":"7857","5dcb72f3":"7895","4031e9f7":"7897","643d8a8d":"7901","1a4e3797":"7920","8f8adbc7":"7946",a278eb8a:"7976",dcc0022e:"7998","1927753e":"8115",dea898c0:"8128","62fe928d":"8143","5485dabc":"8174",a46578cf:"8179","576fbfe0":"8242","35a54963":"8245",d720a69e:"8360","544ce753":"8369","9269c30e":"8377",b8f5ca21:"8430",e4522466:"8460",bec209e4:"8468","39d2b2a1":"8520",e8eb75b8:"8551",a2f4a134:"8562",d7b686af:"8568","3611a290":"8576","1786974b":"8626",e7296c31:"8651",daaec077:"8669","82b8438d":"8706","85522cfa":"8707","0c9e3a88":"8792","43bc6ea7":"8806","74c840dd":"8843",ec3aa2a7:"8890","5091bfe8":"8909","0ff7615f":"8915",a554bc57:"8921","7b9d511f":"8940","1d64ce3b":"8974",cec11939:"9124","2718a84a":"9166","953f1846":"9170",cdfbc197:"9188","1a50ba5c":"9200","60e2c3e9":"9245","32725dec":"9252","91dcd4bd":"9265",c228b49c:"9351","97dbc2fa":"9376",adde0795:"9493",c0f3f8dd:"9507","1be78505":"9514",d8a3c4e8:"9553","5c213362":"9601",b2d3a646:"9609",eb21ac32:"9612",f5707f2d:"9677",f2b9d9a0:"9681","14eb3368":"9817","8bead906":"9819",e6b28b9a:"9826","2d750523":"9943","4d9fef28":"9952","2285ff78":"9961",e819c839:"9964"}[e]||e,r.p+r.u(e)},(()=>{var e={1303:0,532:0};r.f.j=(a,d)=>{var c=r.o(e,a)?e[a]:void 0;if(0!==c)if(c)d.push(c[2]);else if(/^(1303|532)$/.test(a))e[a]=0;else{var f=new Promise(((d,f)=>c=e[a]=[d,f]));d.push(c[2]=f);var b=r.p+r.u(a),t=new Error;r.l(b,(d=>{if(r.o(e,a)&&(0!==(c=e[a])&&(e[a]=void 0),c)){var f=d&&("load"===d.type?"missing":d.type),b=d&&d.target&&d.target.src;t.message="Loading chunk "+a+" failed.\n("+f+": "+b+")",t.name="ChunkLoadError",t.type=f,t.request=b,c[1](t)}}),"chunk-"+a,a)}},r.O.j=a=>0===e[a];var a=(a,d)=>{var c,f,[b,t,o]=d,n=0;if(b.some((a=>0!==e[a]))){for(c in t)r.o(t,c)&&(r.m[c]=t[c]);if(o)var i=o(r)}for(a&&a(d);n{"use strict";var e,a,d,c,f={},b={};function r(e){var a=b[e];if(void 0!==a)return a.exports;var d=b[e]={id:e,loaded:!1,exports:{}};return f[e].call(d.exports,d,d.exports,r),d.loaded=!0,d.exports}r.m=f,r.c=b,e=[],r.O=(a,d,c,f)=>{if(!d){var b=1/0;for(i=0;i=f)&&Object.keys(r.O).every((e=>r.O[e](d[o])))?d.splice(o--,1):(t=!1,f0&&e[i-1][2]>f;i--)e[i]=e[i-1];e[i]=[d,c,f]},r.n=e=>{var a=e&&e.__esModule?()=>e.default:()=>e;return r.d(a,{a:a}),a},d=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,c){if(1&c&&(e=this(e)),8&c)return e;if("object"==typeof e&&e){if(4&c&&e.__esModule)return e;if(16&c&&"function"==typeof e.then)return e}var f=Object.create(null);r.r(f);var b={};a=a||[null,d({}),d([]),d(d)];for(var t=2&c&&e;"object"==typeof t&&!~a.indexOf(t);t=d(t))Object.getOwnPropertyNames(t).forEach((a=>b[a]=()=>e[a]));return b.default=()=>e,r.d(f,b),f},r.d=(e,a)=>{for(var d in a)r.o(a,d)&&!r.o(e,d)&&Object.defineProperty(e,d,{enumerable:!0,get:a[d]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((a,d)=>(r.f[d](e,a),a)),[])),r.u=e=>"assets/js/"+({6:"9b025403",49:"d2466f6f",53:"935f2afb",103:"ea4e3d0a",134:"3f3aaba7",272:"6c584ec9",283:"e3068001",355:"a13d31c2",402:"e90bd361",410:"b5804665",415:"81fa8341",452:"8786b357",496:"09ed2da6",550:"744891a1",573:"8932c20f",576:"f424d1a5",631:"5ef10653",668:"bfdce259",719:"41395dbd",731:"7192b7de",742:"2ac7523a",769:"16ad331b",777:"4fa180b0",785:"cb59c4a0",821:"115cd9a3",823:"dafd2d45",844:"f0db630e",888:"d4b00c8e",936:"58eb6a88",954:"4bd184f6",985:"6c20e6ff",1e3:"f2ed1a45",1042:"8586747a",1049:"b3206f11",1050:"23c664e3",1120:"e16cd061",1185:"f0dd6a1c",1218:"1bcb6c12",1239:"11773138",1290:"2b577994",1321:"313a01e8",1343:"b2ce4c9b",1367:"9cf56202",1400:"bf1edca5",1435:"994031bd",1444:"74feb7e9",1455:"0669159b",1472:"f9670de5",1526:"5375b588",1593:"1289b509",1594:"e576ad5a",1608:"c6c4033b",1642:"807e0e7f",1651:"20f77e87",1658:"af5aa801",1662:"f9d96800",1850:"8210fdb1",1894:"d8146d88",1908:"754a5aa1",1940:"614c5cb3",1981:"52d32b65",2027:"1625e41d",2028:"1b317434",2116:"143fd892",2131:"0bd1d967",2152:"108bd67c",2218:"2b6906c9",2225:"5cd6c63e",2227:"3807d7d6",2252:"bfc3545d",2306:"5239ef28",2308:"94373f1a",2316:"606deeae",2330:"c8ebe515",2365:"ed6862e8",2371:"f6e3ec6f",2400:"b85acdea",2413:"da63d163",2420:"29381d51",2436:"56abd55d",2467:"84527cbe",2474:"e2ce234d",2487:"5192a38d",2496:"b830c51f",2553:"3aff40da",2554:"6a498910",2575:"552c4e0c",2584:"0d5720d7",2625:"f0627f31",2653:"8fa8d26c",2655:"6f6762d6",2657:"18a48af9",2660:"928de919",2685:"f851cefd",2688:"6c93fab4",2771:"a91c4286",2788:"7a39c63d",2796:"4c8950db",2803:"609507dd",2804:"04f4d10e",2810:"3bebfd13",2818:"f9296bce",2886:"fb281095",2924:"a421f136",2935:"99dc5750",3024:"ff72b8c5",3065:"f53fc191",3099:"59394caa",3150:"235a3768",3212:"46df1549",3224:"be187cac",3230:"690d9910",3297:"3cc4a212",3351:"5d391cac",3361:"4c33d3af",3367:"4ff64585",3402:"f2fce86e",3479:"90ebd9bb",3499:"be21ce14",3514:"e7b1c7fb",3535:"787bd795",3539:"49a2de41",3574:"09a3d573",3598:"35be87b0",3624:"3a4485c3",3716:"01b164d8",3815:"6421a520",3916:"a9582fe4",3925:"280ddd3f",4014:"392f1828",4089:"0a830855",4148:"d48f303d",4163:"e00e9744",4199:"6321fd3f",4205:"b5072790",4223:"e8d874da",4295:"d96b90b7",4340:"31f4abdf",4361:"7bb53413",4371:"329a2b2c",4372:"31cac2d3",4387:"9fd49971",4402:"19cdea2a",4404:"97a83304",4415:"45b4adc3",4488:"406269e3",4563:"bb7899cf",4564:"2a2911a0",4567:"81c85956",4585:"c32c8e15",4632:"a8124785",4654:"81d235f1",4673:"fb56a3bd",4679:"a36d4da6",4682:"f85307a1",4727:"df70af35",4728:"acc6ec00",4804:"e601491c",4805:"f0e54ba1",4873:"d9a94183",4894:"25c500d7",4929:"51ec4823",4933:"9667b125",4942:"9e15f089",4998:"8accfa6b",5003:"acfe585e",5149:"81fb6d2e",5160:"dc82b870",5206:"780ab5fe",5211:"ca77dae4",5257:"d30eb9d5",5297:"464acffe",5326:"415d22d3",5393:"7a1f4a4b",5420:"b6abd322",5453:"62637bea",5511:"b605821b",5601:"8b704fbf",5671:"3ba47c53",5719:"f5b0ea4e",5722:"842f7607",5752:"e096712b",5838:"12cd9398",5938:"bf35a50a",5941:"53d239a6",5961:"5a8128fc",5987:"f271fbd1",6002:"9eb21ad8",6003:"1356c1e0",6064:"09b1f4ec",6069:"9daadb77",6129:"c59e05db",6138:"2d780b31",6167:"6ba78147",6199:"49e32276",6252:"1c39fe1c",6296:"1a74ecf5",6302:"3e43c26d",6374:"d3874e59",6391:"5141b302",6397:"de021951",6428:"a13cc575",6460:"f8f2717e",6539:"0a484b7f",6549:"531e34f7",6568:"03a88bad",6571:"56f260e6",6601:"801cd2ac",6603:"ad0d1242",6639:"a75ec5e6",6668:"e40fdf3e",6697:"0a0856d1",6722:"9ad59d1a",6743:"2a1f3a69",6749:"46a1d8da",6760:"97e6230f",6762:"aba198a0",6775:"4f65b59d",6787:"4e289b8c",6824:"8c6e4059",6847:"eefaeb96",6857:"249142be",6971:"7e82ff00",7035:"b3532997",7045:"b0b18499",7073:"32280d2a",7118:"a4c58ea5",7124:"1eba2b69",7181:"61465158",7184:"9efd0bac",7194:"0761ccf0",7226:"bdb71c26",7230:"28cf53e0",7320:"aff97f8f",7351:"80a7c393",7353:"40637d96",7354:"633ab802",7371:"be76f99b",7376:"620c1ecf",7455:"84854274",7466:"a3b3261e",7510:"057e32cd",7548:"e6d95f92",7562:"6336d072",7566:"ed701caf",7593:"a5b875af",7596:"1be1dd71",7603:"bbfb0947",7640:"d7a0e816",7651:"59e4c8ed",7682:"3a190d01",7700:"cb2c64da",7709:"c9607746",7716:"fc25dd3d",7772:"873012db",7786:"cf3e925d",7813:"a9abf8f4",7821:"9d83e1d1",7823:"0e3d8387",7825:"141f29dd",7839:"73da8aa8",7849:"9e212ebb",7857:"02855f38",7895:"5dcb72f3",7897:"4031e9f7",7901:"643d8a8d",7918:"17896441",7920:"1a4e3797",7946:"8f8adbc7",7976:"a278eb8a",7998:"dcc0022e",8115:"1927753e",8128:"dea898c0",8143:"62fe928d",8174:"5485dabc",8179:"a46578cf",8242:"576fbfe0",8245:"35a54963",8360:"d720a69e",8369:"544ce753",8377:"9269c30e",8430:"b8f5ca21",8460:"e4522466",8468:"bec209e4",8520:"39d2b2a1",8551:"e8eb75b8",8562:"a2f4a134",8568:"d7b686af",8576:"3611a290",8626:"1786974b",8635:"10564578",8651:"e7296c31",8669:"daaec077",8671:"83716646",8706:"82b8438d",8707:"85522cfa",8792:"0c9e3a88",8806:"43bc6ea7",8843:"74c840dd",8890:"ec3aa2a7",8909:"5091bfe8",8915:"0ff7615f",8921:"a554bc57",8940:"7b9d511f",8974:"1d64ce3b",9117:"91266340",9124:"cec11939",9166:"2718a84a",9170:"953f1846",9188:"cdfbc197",9200:"1a50ba5c",9245:"60e2c3e9",9252:"32725dec",9265:"91dcd4bd",9351:"c228b49c",9376:"97dbc2fa",9493:"adde0795",9507:"c0f3f8dd",9514:"1be78505",9553:"d8a3c4e8",9601:"5c213362",9609:"b2d3a646",9612:"eb21ac32",9677:"f5707f2d",9681:"f2b9d9a0",9817:"14eb3368",9819:"8bead906",9826:"e6b28b9a",9943:"2d750523",9952:"4d9fef28",9961:"2285ff78",9964:"e819c839"}[e]||e)+"."+{6:"a0809e49",49:"2d2a3a45",53:"cffed61e",103:"6360436d",134:"103641b9",272:"052388cc",283:"5d3cddb4",355:"83a5b992",402:"7cacbae7",410:"37027f65",415:"d22b46f7",452:"197bdf75",496:"f613d5d4",550:"1c06a569",573:"ccc85d41",576:"a19d2041",631:"18cb5a7b",668:"b554ebbc",719:"13b7998a",731:"1d4c9baf",742:"1f7677fe",769:"236aeaaf",777:"b9b640ee",785:"41f7db6d",821:"b4c2a2d9",823:"56cc9b06",844:"bbada611",888:"f3df612a",936:"ec022a34",954:"5b57d984",985:"6f7719bc",1e3:"47a552ed",1042:"5f273b1b",1049:"4761d745",1050:"e69d11df",1120:"ad9e1388",1185:"4fad6916",1218:"fceb2b2d",1239:"f582fce1",1290:"4b25858b",1321:"1541be1d",1343:"bc8720d2",1367:"8f6d2cb8",1400:"9018dfef",1435:"fe57a877",1444:"b327d72b",1455:"803f2bf6",1472:"b96e1fb6",1526:"2d312b7f",1593:"4e2f65a2",1594:"fd2635b1",1608:"8772bfac",1642:"58fd90c2",1651:"b335dc6c",1658:"78907435",1662:"ff7b9072",1850:"4199b587",1894:"544488d4",1908:"fca041e4",1940:"09242807",1981:"23a10be1",2027:"69d4238e",2028:"6fb18cd6",2116:"ca527ced",2131:"d4ec2a3d",2152:"aa370bb3",2218:"d76a1958",2225:"1b3ea5d7",2227:"33d5212d",2252:"4038bfa0",2306:"5b28362d",2308:"b90f861c",2316:"05a55327",2330:"139f1349",2365:"a66d0f4c",2371:"f6b8a2f3",2400:"72298f18",2413:"55471bef",2420:"3e46ebe4",2436:"05996851",2467:"a6938fce",2474:"27584129",2487:"430f9e25",2496:"e16065e3",2553:"3466bb35",2554:"80d285ba",2575:"d0b92952",2584:"fcbaaa52",2625:"bd923c33",2653:"dcc065dc",2655:"7a293757",2657:"6961db7d",2660:"d3845428",2685:"567bbbb5",2688:"e965f644",2771:"7d28ad30",2788:"98f63df4",2796:"2ac46611",2803:"f2a4e177",2804:"ae2aea36",2810:"1368da01",2818:"4e7c4fbd",2886:"e4c7a40e",2924:"8443a925",2935:"9ba9bf29",3024:"b59c8d69",3065:"7eb2b1dc",3099:"dcedb18a",3150:"2034495f",3212:"1293b474",3224:"811d4d3a",3230:"924fadfa",3297:"cdf3e856",3351:"a7843562",3361:"e7f1e7e2",3367:"0ae9319c",3402:"9a63949e",3479:"ed7c1a24",3499:"f80e3b7c",3514:"afe3fcf8",3535:"c007e7a0",3539:"429d356d",3574:"ef16e307",3598:"28210f59",3624:"cc228b34",3716:"8bbb559a",3815:"ef545eb8",3893:"a73ae4a4",3916:"ed3e5873",3925:"b8dde18d",4014:"58608de7",4089:"d025a522",4148:"982fa3ad",4163:"4a7abcd4",4199:"ef41b2e8",4205:"4135f282",4223:"ef67eb11",4295:"fe21b519",4340:"c86ff17a",4361:"1a9e7e6c",4371:"7ceef633",4372:"5526c807",4387:"86cdb06c",4402:"5dd5e414",4404:"f37875c4",4415:"9b1e4a6e",4488:"000c3810",4563:"4c156130",4564:"847dbc59",4567:"0e3fd2b8",4585:"fc51e049",4632:"ad048b7e",4654:"5cd17655",4670:"7505f65b",4673:"157537d4",4679:"6ea7799c",4682:"927e06e7",4727:"24324739",4728:"9548e83c",4804:"f0bbcc86",4805:"b487dc88",4873:"a4028090",4894:"e5068d91",4929:"bae29a52",4933:"5fecbf67",4942:"997a7776",4998:"64a2f0f1",5003:"24868a24",5149:"1e446259",5160:"e2bc29d4",5206:"8857d8bf",5211:"240d56a8",5257:"0d5d93f5",5297:"6072b626",5326:"c05ba79a",5393:"03799846",5420:"bdb25c6a",5453:"5e5acd1f",5511:"e8ada5dc",5601:"612e5f6f",5671:"a236af23",5719:"c48022f0",5722:"ff473bb1",5752:"73d81066",5838:"572beee5",5938:"24925353",5941:"5f2c9ebe",5961:"4439422b",5987:"8c515fda",6002:"cb5e5945",6003:"f2bb6af3",6064:"38c6f47d",6069:"f5b11f86",6129:"c892cbdc",6138:"cb4bec8c",6167:"b9f2451d",6199:"dac02bbd",6252:"c75a8b9d",6296:"32e047e0",6302:"c858dede",6374:"c10ff622",6391:"64715933",6397:"cf2919d3",6428:"d8b3e1a0",6460:"b67fef84",6539:"4d688384",6549:"7bfa0a02",6568:"c29ece07",6571:"ad423613",6601:"76649944",6603:"a09045cf",6639:"0d88c64a",6668:"ca106e53",6697:"09b90ec2",6722:"610a4dfc",6743:"75668e44",6749:"96c171af",6760:"83cdcc2f",6762:"b4819cf4",6775:"e3893092",6787:"b2f5880a",6824:"6809fc15",6847:"1ff8550f",6857:"fc1a4755",6971:"eef9a167",7035:"04181932",7045:"6f842660",7073:"5614810e",7118:"bb8cf260",7124:"85699964",7181:"7f811852",7184:"c13466db",7194:"4d561a7d",7226:"e5f89144",7230:"ae10d3cb",7320:"3e1e5511",7351:"f88e1a60",7353:"fc1e18b5",7354:"e320b6f5",7371:"49b6db93",7376:"129738cc",7455:"82275863",7466:"ee217c5e",7510:"5a7b38d8",7548:"5e9064f6",7562:"423dc099",7566:"93a7c99e",7593:"84cd8c35",7596:"c6999d10",7603:"348598d6",7640:"4d7767cc",7651:"1103dc59",7682:"49ac0517",7700:"28126961",7709:"92610cca",7716:"f84b5e75",7772:"7857929a",7786:"1bfcc28d",7813:"c0fb5b58",7821:"85124642",7823:"2033f2c0",7825:"c272b72c",7839:"3cb9aad7",7849:"0876a544",7857:"d047e27b",7895:"68aa0a9b",7897:"55d3e243",7901:"11307c6e",7918:"54dd059c",7920:"c7887816",7946:"b8366875",7976:"02fc1ce7",7998:"f7e6e8e3",8115:"5c0e1035",8128:"b8b74bee",8143:"be0b0fa9",8174:"13168adb",8179:"1ad43b76",8242:"fbbc4aec",8245:"cdd4601b",8360:"de8cdf51",8369:"c94fe608",8377:"035d7d6a",8430:"48156def",8460:"b77ca010",8468:"cbd72add",8520:"88bc633b",8551:"3d0ab95d",8562:"e4da1372",8568:"a15cae71",8576:"9d19d9a9",8626:"e2664616",8635:"ddf80469",8651:"8799e2f5",8669:"1006f8eb",8671:"e5ec4f73",8706:"90b4e0d9",8707:"d47843b9",8777:"2a45b830",8792:"ae3b390e",8806:"084fb41f",8843:"db02c810",8890:"0bfcf124",8909:"a5e21bbd",8915:"6d5489c6",8921:"7a8ad8d6",8940:"7baf1fc1",8974:"f816bfd6",9117:"5f323c3f",9124:"15b46b55",9127:"51d941eb",9166:"ca40ab90",9170:"7ceae35c",9188:"30898979",9200:"6ddcec01",9245:"e99e4a3b",9252:"0479c08c",9265:"752d7b48",9351:"19aae2a1",9376:"2a9f630d",9493:"534949ef",9507:"e030864f",9514:"40118b63",9553:"57d90fd5",9601:"aa596d2b",9609:"95f18f5a",9612:"b5eb15ee",9677:"02bd9f4c",9681:"a3d127ee",9817:"6bc6a528",9819:"3783749c",9826:"e6b0577e",9943:"db170a85",9952:"ee9354a8",9961:"bc231ea8",9964:"3b8d47ab"}[e]+".js",r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,a)=>Object.prototype.hasOwnProperty.call(e,a),c={},r.l=(e,a,d,f)=>{if(c[e])c[e].push(a);else{var b,t;if(void 0!==d)for(var o=document.getElementsByTagName("script"),n=0;n{b.onerror=b.onload=null,clearTimeout(u);var f=c[e];if(delete c[e],b.parentNode&&b.parentNode.removeChild(b),f&&f.forEach((e=>e(d))),a)return a(d)},u=setTimeout(l.bind(null,void 0,{type:"timeout",target:b}),12e4);b.onerror=l.bind(null,b.onerror),b.onload=l.bind(null,b.onload),t&&document.head.appendChild(b)}},r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.p="/",r.gca=function(e){return e={10564578:"8635",11773138:"1239",17896441:"7918",61465158:"7181",83716646:"8671",84854274:"7455",91266340:"9117","9b025403":"6",d2466f6f:"49","935f2afb":"53",ea4e3d0a:"103","3f3aaba7":"134","6c584ec9":"272",e3068001:"283",a13d31c2:"355",e90bd361:"402",b5804665:"410","81fa8341":"415","8786b357":"452","09ed2da6":"496","744891a1":"550","8932c20f":"573",f424d1a5:"576","5ef10653":"631",bfdce259:"668","41395dbd":"719","7192b7de":"731","2ac7523a":"742","16ad331b":"769","4fa180b0":"777",cb59c4a0:"785","115cd9a3":"821",dafd2d45:"823",f0db630e:"844",d4b00c8e:"888","58eb6a88":"936","4bd184f6":"954","6c20e6ff":"985",f2ed1a45:"1000","8586747a":"1042",b3206f11:"1049","23c664e3":"1050",e16cd061:"1120",f0dd6a1c:"1185","1bcb6c12":"1218","2b577994":"1290","313a01e8":"1321",b2ce4c9b:"1343","9cf56202":"1367",bf1edca5:"1400","994031bd":"1435","74feb7e9":"1444","0669159b":"1455",f9670de5:"1472","5375b588":"1526","1289b509":"1593",e576ad5a:"1594",c6c4033b:"1608","807e0e7f":"1642","20f77e87":"1651",af5aa801:"1658",f9d96800:"1662","8210fdb1":"1850",d8146d88:"1894","754a5aa1":"1908","614c5cb3":"1940","52d32b65":"1981","1625e41d":"2027","1b317434":"2028","143fd892":"2116","0bd1d967":"2131","108bd67c":"2152","2b6906c9":"2218","5cd6c63e":"2225","3807d7d6":"2227",bfc3545d:"2252","5239ef28":"2306","94373f1a":"2308","606deeae":"2316",c8ebe515:"2330",ed6862e8:"2365",f6e3ec6f:"2371",b85acdea:"2400",da63d163:"2413","29381d51":"2420","56abd55d":"2436","84527cbe":"2467",e2ce234d:"2474","5192a38d":"2487",b830c51f:"2496","3aff40da":"2553","6a498910":"2554","552c4e0c":"2575","0d5720d7":"2584",f0627f31:"2625","8fa8d26c":"2653","6f6762d6":"2655","18a48af9":"2657","928de919":"2660",f851cefd:"2685","6c93fab4":"2688",a91c4286:"2771","7a39c63d":"2788","4c8950db":"2796","609507dd":"2803","04f4d10e":"2804","3bebfd13":"2810",f9296bce:"2818",fb281095:"2886",a421f136:"2924","99dc5750":"2935",ff72b8c5:"3024",f53fc191:"3065","59394caa":"3099","235a3768":"3150","46df1549":"3212",be187cac:"3224","690d9910":"3230","3cc4a212":"3297","5d391cac":"3351","4c33d3af":"3361","4ff64585":"3367",f2fce86e:"3402","90ebd9bb":"3479",be21ce14:"3499",e7b1c7fb:"3514","787bd795":"3535","49a2de41":"3539","09a3d573":"3574","35be87b0":"3598","3a4485c3":"3624","01b164d8":"3716","6421a520":"3815",a9582fe4:"3916","280ddd3f":"3925","392f1828":"4014","0a830855":"4089",d48f303d:"4148",e00e9744:"4163","6321fd3f":"4199",b5072790:"4205",e8d874da:"4223",d96b90b7:"4295","31f4abdf":"4340","7bb53413":"4361","329a2b2c":"4371","31cac2d3":"4372","9fd49971":"4387","19cdea2a":"4402","97a83304":"4404","45b4adc3":"4415","406269e3":"4488",bb7899cf:"4563","2a2911a0":"4564","81c85956":"4567",c32c8e15:"4585",a8124785:"4632","81d235f1":"4654",fb56a3bd:"4673",a36d4da6:"4679",f85307a1:"4682",df70af35:"4727",acc6ec00:"4728",e601491c:"4804",f0e54ba1:"4805",d9a94183:"4873","25c500d7":"4894","51ec4823":"4929","9667b125":"4933","9e15f089":"4942","8accfa6b":"4998",acfe585e:"5003","81fb6d2e":"5149",dc82b870:"5160","780ab5fe":"5206",ca77dae4:"5211",d30eb9d5:"5257","464acffe":"5297","415d22d3":"5326","7a1f4a4b":"5393",b6abd322:"5420","62637bea":"5453",b605821b:"5511","8b704fbf":"5601","3ba47c53":"5671",f5b0ea4e:"5719","842f7607":"5722",e096712b:"5752","12cd9398":"5838",bf35a50a:"5938","53d239a6":"5941","5a8128fc":"5961",f271fbd1:"5987","9eb21ad8":"6002","1356c1e0":"6003","09b1f4ec":"6064","9daadb77":"6069",c59e05db:"6129","2d780b31":"6138","6ba78147":"6167","49e32276":"6199","1c39fe1c":"6252","1a74ecf5":"6296","3e43c26d":"6302",d3874e59:"6374","5141b302":"6391",de021951:"6397",a13cc575:"6428",f8f2717e:"6460","0a484b7f":"6539","531e34f7":"6549","03a88bad":"6568","56f260e6":"6571","801cd2ac":"6601",ad0d1242:"6603",a75ec5e6:"6639",e40fdf3e:"6668","0a0856d1":"6697","9ad59d1a":"6722","2a1f3a69":"6743","46a1d8da":"6749","97e6230f":"6760",aba198a0:"6762","4f65b59d":"6775","4e289b8c":"6787","8c6e4059":"6824",eefaeb96:"6847","249142be":"6857","7e82ff00":"6971",b3532997:"7035",b0b18499:"7045","32280d2a":"7073",a4c58ea5:"7118","1eba2b69":"7124","9efd0bac":"7184","0761ccf0":"7194",bdb71c26:"7226","28cf53e0":"7230",aff97f8f:"7320","80a7c393":"7351","40637d96":"7353","633ab802":"7354",be76f99b:"7371","620c1ecf":"7376",a3b3261e:"7466","057e32cd":"7510",e6d95f92:"7548","6336d072":"7562",ed701caf:"7566",a5b875af:"7593","1be1dd71":"7596",bbfb0947:"7603",d7a0e816:"7640","59e4c8ed":"7651","3a190d01":"7682",cb2c64da:"7700",c9607746:"7709",fc25dd3d:"7716","873012db":"7772",cf3e925d:"7786",a9abf8f4:"7813","9d83e1d1":"7821","0e3d8387":"7823","141f29dd":"7825","73da8aa8":"7839","9e212ebb":"7849","02855f38":"7857","5dcb72f3":"7895","4031e9f7":"7897","643d8a8d":"7901","1a4e3797":"7920","8f8adbc7":"7946",a278eb8a:"7976",dcc0022e:"7998","1927753e":"8115",dea898c0:"8128","62fe928d":"8143","5485dabc":"8174",a46578cf:"8179","576fbfe0":"8242","35a54963":"8245",d720a69e:"8360","544ce753":"8369","9269c30e":"8377",b8f5ca21:"8430",e4522466:"8460",bec209e4:"8468","39d2b2a1":"8520",e8eb75b8:"8551",a2f4a134:"8562",d7b686af:"8568","3611a290":"8576","1786974b":"8626",e7296c31:"8651",daaec077:"8669","82b8438d":"8706","85522cfa":"8707","0c9e3a88":"8792","43bc6ea7":"8806","74c840dd":"8843",ec3aa2a7:"8890","5091bfe8":"8909","0ff7615f":"8915",a554bc57:"8921","7b9d511f":"8940","1d64ce3b":"8974",cec11939:"9124","2718a84a":"9166","953f1846":"9170",cdfbc197:"9188","1a50ba5c":"9200","60e2c3e9":"9245","32725dec":"9252","91dcd4bd":"9265",c228b49c:"9351","97dbc2fa":"9376",adde0795:"9493",c0f3f8dd:"9507","1be78505":"9514",d8a3c4e8:"9553","5c213362":"9601",b2d3a646:"9609",eb21ac32:"9612",f5707f2d:"9677",f2b9d9a0:"9681","14eb3368":"9817","8bead906":"9819",e6b28b9a:"9826","2d750523":"9943","4d9fef28":"9952","2285ff78":"9961",e819c839:"9964"}[e]||e,r.p+r.u(e)},(()=>{var e={1303:0,532:0};r.f.j=(a,d)=>{var c=r.o(e,a)?e[a]:void 0;if(0!==c)if(c)d.push(c[2]);else if(/^(1303|532)$/.test(a))e[a]=0;else{var f=new Promise(((d,f)=>c=e[a]=[d,f]));d.push(c[2]=f);var b=r.p+r.u(a),t=new Error;r.l(b,(d=>{if(r.o(e,a)&&(0!==(c=e[a])&&(e[a]=void 0),c)){var f=d&&("load"===d.type?"missing":d.type),b=d&&d.target&&d.target.src;t.message="Loading chunk "+a+" failed.\n("+f+": "+b+")",t.name="ChunkLoadError",t.type=f,t.request=b,c[1](t)}}),"chunk-"+a,a)}},r.O.j=a=>0===e[a];var a=(a,d)=>{var c,f,[b,t,o]=d,n=0;if(b.some((a=>0!==e[a]))){for(c in t)r.o(t,c)&&(r.m[c]=t[c]);if(o)var i=o(r)}for(a&&a(d);ncheck API | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

validationResult(req)

Extracts the validation errors from a request and makes it available in the form of a validation result object.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator/check');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/5.2.0/custom-error-messages/index.html b/docs/5.2.0/custom-error-messages/index.html index f4e6d07..35aa5c7 100644 --- a/docs/5.2.0/custom-error-messages/index.html +++ b/docs/5.2.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/5.2.0/custom-validators-sanitizers/index.html b/docs/5.2.0/custom-validators-sanitizers/index.html index 9958dc8..4c8162c 100644 --- a/docs/5.2.0/custom-validators-sanitizers/index.html +++ b/docs/5.2.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { sanitizeParam } = require('express-validator/filter');

app.post('/object/:id', sanitizeParam('id').customSanitizer(value => {
return ObjectId(id);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/5.2.0/filter-api/index.html b/docs/5.2.0/filter-api/index.html index cda6457..e7d0b6f 100644 --- a/docs/5.2.0/filter-api/index.html +++ b/docs/5.2.0/filter-api/index.html @@ -6,7 +6,7 @@ filter API | express-validator - + @@ -17,7 +17,7 @@ an object with them. Nested paths and wildcards are properly handled as well.

// Suppose the request looks like this:
// req.query = { from: '2017-01-12' }
// req.body = { to: '2017-31-12' }

app.post('/room-availability', check(['from', 'to']).isISO8601(), (req, res, next) => {
const queryData = matchedData(req, { locations: ['query'] });
const bodyData = matchedData(req, { locations: ['body'] });
const allData = matchedData(req);
console.log(queryData); // { from: '2017-01-12' }
console.log(bodyData); // { to: '2017-31-12' }
console.log(allData); // { from: '2017-01-12', to: '2017-31-12' }
});

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator/filter');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/5.2.0/index.html b/docs/5.2.0/index.html index 4183933..cce14c2 100644 --- a/docs/5.2.0/index.html +++ b/docs/5.2.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/5.2.0/legacy-api/index.html b/docs/5.2.0/legacy-api/index.html index 5e240ba..baef1a3 100644 --- a/docs/5.2.0/legacy-api/index.html +++ b/docs/5.2.0/legacy-api/index.html @@ -6,7 +6,7 @@ Legacy API | express-validator - + @@ -19,7 +19,7 @@ This probably means any async validator will not be completed by the time this method responds.

Schema validation

All req.check methods can do schema validation. The schema syntax is the same as described in Schema Validation.

- + \ No newline at end of file diff --git a/docs/5.2.0/sanitization-chain-api/index.html b/docs/5.2.0/sanitization-chain-api/index.html index b38a2a2..f721846 100644 --- a/docs/5.2.0/sanitization-chain-api/index.html +++ b/docs/5.2.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -15,7 +15,7 @@ When the middleware runs, it will modify each field in place, applying each of the sanitizers in the order they were specified:

app.get('/', sanitizeBody('trimMe').trim(), (req, res, next) => {
// If req.body.trimMe was originally " something ",
// its sanitized value will be "something"
console.log(req.body.trimMe);
});

Any of the sanitization methods listed by validator.js are made available in all sanitization chains created by express-validator, as long as we're supporting the most up-to-date validator version.

Additionally, the following methods are also available:

.customSanitizer(sanitizer)

  • sanitizer(value, { req, location, path }): the custom sanitizer function.
    Receives the value of the field being sanitized, as well as the express request, the location and the field path.

    Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

app.get('/object/:id', sanitizeParam('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)
- + \ No newline at end of file diff --git a/docs/5.2.0/sanitization/index.html b/docs/5.2.0/sanitization/index.html index 179198b..d80fc2a 100644 --- a/docs/5.2.0/sanitization/index.html +++ b/docs/5.2.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/5.2.0/schema-validation/index.html b/docs/5.2.0/schema-validation/index.html index fb8d9a2..8308cb6 100644 --- a/docs/5.2.0/schema-validation/index.html +++ b/docs/5.2.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntaxs looks like this:

const { checkSchema } = require('express-validator/check');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
optional: true,
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/5.2.0/validation-chain-api/index.html b/docs/5.2.0/validation-chain-api/index.html index 6f59946..4874758 100644 --- a/docs/5.2.0/validation-chain-api/index.html +++ b/docs/5.2.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -20,7 +20,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/5.2.0/validation-result-api/index.html b/docs/5.2.0/validation-result-api/index.html index 40cd493..e138980 100644 --- a/docs/5.2.0/validation-result-api/index.html +++ b/docs/5.2.0/validation-result-api/index.html @@ -6,7 +6,7 @@ Validation Result API | express-validator - + @@ -16,7 +16,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}

.withDefaults(options)

  • options (optional): an object of options. Defaults to { formatter: error => error }

    Returns: a new validationResult function is returned, using the provided options

This is useful when you have a consistent set of options you would like to use for all validation results throughout your application.

Below is an example which sets a default error formatter:

const { validationResult } = require('express-validator/check');

const result = validationResult.withDefaults({
formatter: (error) => {
return {
myLocation: error.location,
};
}
});

module.exports = result;
- + \ No newline at end of file diff --git a/docs/5.2.0/whole-body-validation/index.html b/docs/5.2.0/whole-body-validation/index.html index 488ea93..d4e3d86 100644 --- a/docs/5.2.0/whole-body-validation/index.html +++ b/docs/5.2.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator/check');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/5.2.0/wildcards/index.html b/docs/5.2.0/wildcards/index.html index 3cd607c..254589c 100644 --- a/docs/5.2.0/wildcards/index.html +++ b/docs/5.2.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer number.

We can do this with the following code:

const express = require('express');
const { check } = require('express-validator/check');
const { sanitize } = require('express-validator/filter');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/5.3.0/check-api/index.html b/docs/5.3.0/check-api/index.html index eae0071..61736c2 100644 --- a/docs/5.3.0/check-api/index.html +++ b/docs/5.3.0/check-api/index.html @@ -6,7 +6,7 @@ check API | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

validationResult(req)

Extracts the validation errors from a request and makes it available in the form of a validation result object.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator/check');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/5.3.0/custom-error-messages/index.html b/docs/5.3.0/custom-error-messages/index.html index 46d2c59..cf38ce3 100644 --- a/docs/5.3.0/custom-error-messages/index.html +++ b/docs/5.3.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/5.3.0/custom-validators-sanitizers/index.html b/docs/5.3.0/custom-validators-sanitizers/index.html index 94eb379..03064a0 100644 --- a/docs/5.3.0/custom-validators-sanitizers/index.html +++ b/docs/5.3.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { sanitizeParam } = require('express-validator/filter');

app.post('/object/:id', sanitizeParam('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/5.3.0/filter-api/index.html b/docs/5.3.0/filter-api/index.html index 1ce1a11..fee19da 100644 --- a/docs/5.3.0/filter-api/index.html +++ b/docs/5.3.0/filter-api/index.html @@ -6,7 +6,7 @@ filter API | express-validator - + @@ -17,7 +17,7 @@ an object with them. Nested paths and wildcards are properly handled as well.

// Suppose the request looks like this:
// req.query = { from: '2017-01-12' }
// req.body = { to: '2017-31-12' }

app.post('/room-availability', check(['from', 'to']).isISO8601(), (req, res, next) => {
const queryData = matchedData(req, { locations: ['query'] });
const bodyData = matchedData(req, { locations: ['body'] });
const allData = matchedData(req);
console.log(queryData); // { from: '2017-01-12' }
console.log(bodyData); // { to: '2017-31-12' }
console.log(allData); // { from: '2017-01-12', to: '2017-31-12' }
});

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator/filter');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/5.3.0/index.html b/docs/5.3.0/index.html index bfa124a..6eaae98 100644 --- a/docs/5.3.0/index.html +++ b/docs/5.3.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/5.3.0/legacy-api/index.html b/docs/5.3.0/legacy-api/index.html index 0fb72a5..1ea8dde 100644 --- a/docs/5.3.0/legacy-api/index.html +++ b/docs/5.3.0/legacy-api/index.html @@ -6,7 +6,7 @@ Legacy API | express-validator - + @@ -19,7 +19,7 @@ This probably means any async validator will not be completed by the time this method responds.

Schema validation

All req.check methods can do schema validation. The schema syntax is the same as described in Schema Validation.

- + \ No newline at end of file diff --git a/docs/5.3.0/sanitization-chain-api/index.html b/docs/5.3.0/sanitization-chain-api/index.html index a86822e..868a52b 100644 --- a/docs/5.3.0/sanitization-chain-api/index.html +++ b/docs/5.3.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -15,7 +15,7 @@ When the middleware runs, it will modify each field in place, applying each of the sanitizers in the order they were specified:

app.get('/', sanitizeBody('trimMe').trim(), (req, res, next) => {
// If req.body.trimMe was originally " something ",
// its sanitized value will be "something"
console.log(req.body.trimMe);
});

Any of the sanitization methods listed by validator.js are made available in all sanitization chains created by express-validator, as long as we're supporting the most up-to-date validator version.

Additionally, the following methods are also available:

.customSanitizer(sanitizer)

  • sanitizer(value, { req, location, path }): the custom sanitizer function.
    Receives the value of the field being sanitized, as well as the express request, the location and the field path.

    Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

app.get('/object/:id', sanitizeParam('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)
- + \ No newline at end of file diff --git a/docs/5.3.0/sanitization/index.html b/docs/5.3.0/sanitization/index.html index a28fe00..5d61fc6 100644 --- a/docs/5.3.0/sanitization/index.html +++ b/docs/5.3.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/5.3.0/schema-validation/index.html b/docs/5.3.0/schema-validation/index.html index c94cd48..02d2fc5 100644 --- a/docs/5.3.0/schema-validation/index.html +++ b/docs/5.3.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntaxs looks like this:

const { checkSchema } = require('express-validator/check');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
optional: true,
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/5.3.0/validation-chain-api/index.html b/docs/5.3.0/validation-chain-api/index.html index ce517e3..12a5df1 100644 --- a/docs/5.3.0/validation-chain-api/index.html +++ b/docs/5.3.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -20,7 +20,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/5.3.0/validation-result-api/index.html b/docs/5.3.0/validation-result-api/index.html index 89b5152..2f840fd 100644 --- a/docs/5.3.0/validation-result-api/index.html +++ b/docs/5.3.0/validation-result-api/index.html @@ -6,7 +6,7 @@ Validation Result API | express-validator - + @@ -16,7 +16,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}

.withDefaults(options)

  • options (optional): an object of options. Defaults to { formatter: error => error }

    Returns: a new validationResult function is returned, using the provided options

This is useful when you have a consistent set of options you would like to use for all validation results throughout your application.

Below is an example which sets a default error formatter:

const { validationResult } = require('express-validator/check');

const result = validationResult.withDefaults({
formatter: (error) => {
return {
myLocation: error.location,
};
}
});

module.exports = result;
- + \ No newline at end of file diff --git a/docs/5.3.0/whole-body-validation/index.html b/docs/5.3.0/whole-body-validation/index.html index 16cc435..8a40e18 100644 --- a/docs/5.3.0/whole-body-validation/index.html +++ b/docs/5.3.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator/check');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/5.3.0/wildcards/index.html b/docs/5.3.0/wildcards/index.html index 966b4b0..53d134a 100644 --- a/docs/5.3.0/wildcards/index.html +++ b/docs/5.3.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer number.

We can do this with the following code:

const express = require('express');
const { check } = require('express-validator/check');
const { sanitize } = require('express-validator/filter');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.0.0/check-api/index.html b/docs/6.0.0/check-api/index.html index f8948ae..93e49bb 100644 --- a/docs/6.0.0/check-api/index.html +++ b/docs/6.0.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.0.0/custom-error-messages/index.html b/docs/6.0.0/custom-error-messages/index.html index d4a1b21..5177062 100644 --- a/docs/6.0.0/custom-error-messages/index.html +++ b/docs/6.0.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.0.0/custom-validators-sanitizers/index.html b/docs/6.0.0/custom-validators-sanitizers/index.html index 050b61a..7e074e5 100644 --- a/docs/6.0.0/custom-validators-sanitizers/index.html +++ b/docs/6.0.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { sanitizeParam } = require('express-validator');

app.post('/object/:id', sanitizeParam('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.0.0/filter-api/index.html b/docs/6.0.0/filter-api/index.html index 56a956a..255036b 100644 --- a/docs/6.0.0/filter-api/index.html +++ b/docs/6.0.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -14,7 +14,7 @@
Version: 6.0.0

Sanitization middlewares

These methods are all available via require('express-validator').

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.0.0/index.html b/docs/6.0.0/index.html index 6e2f479..e3753b9 100644 --- a/docs/6.0.0/index.html +++ b/docs/6.0.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.0.0/matched-data-api/index.html b/docs/6.0.0/matched-data-api/index.html index ee6873e..bee35de 100644 --- a/docs/6.0.0/matched-data-api/index.html +++ b/docs/6.0.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.0.0/running-imperatively/index.html b/docs/6.0.0/running-imperatively/index.html index 3f180b8..458fbae 100644 --- a/docs/6.0.0/running-imperatively/index.html +++ b/docs/6.0.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.0.0/sanitization-chain-api/index.html b/docs/6.0.0/sanitization-chain-api/index.html index 9b33a9b..6d82c65 100644 --- a/docs/6.0.0/sanitization-chain-api/index.html +++ b/docs/6.0.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

app.get('/object/:id', sanitizeParam('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await sanitize('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});
- + \ No newline at end of file diff --git a/docs/6.0.0/sanitization/index.html b/docs/6.0.0/sanitization/index.html index adc0469..a9ebcf8 100644 --- a/docs/6.0.0/sanitization/index.html +++ b/docs/6.0.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.0.0/schema-validation/index.html b/docs/6.0.0/schema-validation/index.html index 2c8bc36..823fdb6 100644 --- a/docs/6.0.0/schema-validation/index.html +++ b/docs/6.0.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntaxs looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.0.0/validation-chain-api/index.html b/docs/6.0.0/validation-chain-api/index.html index e1bb192..3076b61 100644 --- a/docs/6.0.0/validation-chain-api/index.html +++ b/docs/6.0.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -26,7 +26,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.0.0/validation-result-api/index.html b/docs/6.0.0/validation-result-api/index.html index 7bc5df2..9596d56 100644 --- a/docs/6.0.0/validation-result-api/index.html +++ b/docs/6.0.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.0.0/whole-body-validation/index.html b/docs/6.0.0/whole-body-validation/index.html index 1b8097c..6b711d2 100644 --- a/docs/6.0.0/whole-body-validation/index.html +++ b/docs/6.0.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.0.0/wildcards/index.html b/docs/6.0.0/wildcards/index.html index afef69f..6d01e4c 100644 --- a/docs/6.0.0/wildcards/index.html +++ b/docs/6.0.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer number.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.1.0/check-api/index.html b/docs/6.1.0/check-api/index.html index 1b530a3..8a6308a 100644 --- a/docs/6.1.0/check-api/index.html +++ b/docs/6.1.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.1.0/custom-error-messages/index.html b/docs/6.1.0/custom-error-messages/index.html index d315003..0834a88 100644 --- a/docs/6.1.0/custom-error-messages/index.html +++ b/docs/6.1.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.1.0/custom-validators-sanitizers/index.html b/docs/6.1.0/custom-validators-sanitizers/index.html index c464f65..b783507 100644 --- a/docs/6.1.0/custom-validators-sanitizers/index.html +++ b/docs/6.1.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { sanitizeParam } = require('express-validator');

app.post('/object/:id', sanitizeParam('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.1.0/filter-api/index.html b/docs/6.1.0/filter-api/index.html index d6d4b57..0844ea2 100644 --- a/docs/6.1.0/filter-api/index.html +++ b/docs/6.1.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -14,7 +14,7 @@
Version: 6.1.0

Sanitization middlewares

These methods are all available via require('express-validator').

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.1.0/index.html b/docs/6.1.0/index.html index 03e3110..bc454f0 100644 --- a/docs/6.1.0/index.html +++ b/docs/6.1.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.1.0/matched-data-api/index.html b/docs/6.1.0/matched-data-api/index.html index 876c4bf..1c7c98f 100644 --- a/docs/6.1.0/matched-data-api/index.html +++ b/docs/6.1.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.1.0/running-imperatively/index.html b/docs/6.1.0/running-imperatively/index.html index c32bdc3..db23a74 100644 --- a/docs/6.1.0/running-imperatively/index.html +++ b/docs/6.1.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.1.0/sanitization-chain-api/index.html b/docs/6.1.0/sanitization-chain-api/index.html index 78903ee..2dfb43a 100644 --- a/docs/6.1.0/sanitization-chain-api/index.html +++ b/docs/6.1.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

app.get('/object/:id', sanitizeParam('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await sanitize('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});
- + \ No newline at end of file diff --git a/docs/6.1.0/sanitization/index.html b/docs/6.1.0/sanitization/index.html index 3a38ca5..236149e 100644 --- a/docs/6.1.0/sanitization/index.html +++ b/docs/6.1.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.1.0/schema-validation/index.html b/docs/6.1.0/schema-validation/index.html index a6c1ab2..fb18388 100644 --- a/docs/6.1.0/schema-validation/index.html +++ b/docs/6.1.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntaxs looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.1.0/validation-chain-api/index.html b/docs/6.1.0/validation-chain-api/index.html index 0e1af07..69a764e 100644 --- a/docs/6.1.0/validation-chain-api/index.html +++ b/docs/6.1.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -28,7 +28,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.1.0/validation-result-api/index.html b/docs/6.1.0/validation-result-api/index.html index a1b3ba2..8593d13 100644 --- a/docs/6.1.0/validation-result-api/index.html +++ b/docs/6.1.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.1.0/whole-body-validation/index.html b/docs/6.1.0/whole-body-validation/index.html index c1b7a08..5168c35 100644 --- a/docs/6.1.0/whole-body-validation/index.html +++ b/docs/6.1.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.1.0/wildcards/index.html b/docs/6.1.0/wildcards/index.html index bc4e9a6..3b4bca9 100644 --- a/docs/6.1.0/wildcards/index.html +++ b/docs/6.1.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer number.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.10.0/check-api/index.html b/docs/6.10.0/check-api/index.html index a66c207..b6d6a81 100644 --- a/docs/6.10.0/check-api/index.html +++ b/docs/6.10.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.10.0/custom-error-messages/index.html b/docs/6.10.0/custom-error-messages/index.html index a464a28..498d852 100644 --- a/docs/6.10.0/custom-error-messages/index.html +++ b/docs/6.10.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -25,7 +25,7 @@ For example you can provide an object with multiple properties:

// check(field, withMessage) and .withMessage() work the same
check('email').isEmail().withMessage({
message: 'Not an email',
errorCode: 1,
})
- + \ No newline at end of file diff --git a/docs/6.10.0/custom-validators-sanitizers/index.html b/docs/6.10.0/custom-validators-sanitizers/index.html index 0ad9f30..454bec9 100644 --- a/docs/6.10.0/custom-validators-sanitizers/index.html +++ b/docs/6.10.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
- + \ No newline at end of file diff --git a/docs/6.10.0/faq/index.html b/docs/6.10.0/faq/index.html index a4ea287..5faef6c 100644 --- a/docs/6.10.0/faq/index.html +++ b/docs/6.10.0/faq/index.html @@ -6,7 +6,7 @@ FAQ | express-validator - + @@ -15,7 +15,7 @@ In the second one, instead, all the elements are validated and the chain correctly returns an error.

Referenced issues:

#791, #883, #931

- + \ No newline at end of file diff --git a/docs/6.10.0/filter-api/index.html b/docs/6.10.0/filter-api/index.html index 498ee19..782f449 100644 --- a/docs/6.10.0/filter-api/index.html +++ b/docs/6.10.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.10.0/index.html b/docs/6.10.0/index.html index 97665bb..d8c5dd8 100644 --- a/docs/6.10.0/index.html +++ b/docs/6.10.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.10.0/matched-data-api/index.html b/docs/6.10.0/matched-data-api/index.html index be7eb25..1132c07 100644 --- a/docs/6.10.0/matched-data-api/index.html +++ b/docs/6.10.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post(
'/update-user',
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
(req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
},
);
- + \ No newline at end of file diff --git a/docs/6.10.0/migration-v5-to-v6/index.html b/docs/6.10.0/migration-v5-to-v6/index.html index 2117103..a9fb24e 100644 --- a/docs/6.10.0/migration-v5-to-v6/index.html +++ b/docs/6.10.0/migration-v5-to-v6/index.html @@ -6,7 +6,7 @@ Migration from v5 to v6 | express-validator - + @@ -23,7 +23,7 @@ to learn about other breaking changes.

- + \ No newline at end of file diff --git a/docs/6.10.0/running-imperatively/index.html b/docs/6.10.0/running-imperatively/index.html index e1c3657..e8a265d 100644 --- a/docs/6.10.0/running-imperatively/index.html +++ b/docs/6.10.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain, sanitization chain, checkSchema and oneOf.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

const express = require('express');
const { validateResult, ValidationChain } = require('express-validator');
// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};
app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post(
'/update-settings',
body('email').isEmail(),
body('password').optional().isLength({ min: 6 }),
async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password)
.withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
},
);
- + \ No newline at end of file diff --git a/docs/6.10.0/sanitization-chain-api/index.html b/docs/6.10.0/sanitization-chain-api/index.html index 20ba8ae..617b6f7 100644 --- a/docs/6.10.0/sanitization-chain-api/index.html +++ b/docs/6.10.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get(
'/object/:id',
param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}),
objectHandler,
);

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', body('username').default('foo'), (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'
});

.replace(values_to_replace, new_value)

Returns: the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

app.post('/', body('username').replace(['bar', 'BAR'], 'foo'), (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.10.0/sanitization/index.html b/docs/6.10.0/sanitization/index.html index 2185904..63861a3 100644 --- a/docs/6.10.0/sanitization/index.html +++ b/docs/6.10.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.10.0/schema-validation/index.html b/docs/6.10.0/schema-validation/index.html index ee1da7e..f50e524 100644 --- a/docs/6.10.0/schema-validation/index.html +++ b/docs/6.10.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put(
'/user/:id/password',
checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true,
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
},
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 },
},
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true,
},
}),
(req, res, next) => {
// handle the request as usual
},
);
- + \ No newline at end of file diff --git a/docs/6.10.0/validation-chain-api/index.html b/docs/6.10.0/validation-chain-api/index.html index 17ce010..3d79f53 100644 --- a/docs/6.10.0/validation-chain-api/index.html +++ b/docs/6.10.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -32,7 +32,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.10.0/validation-result-api/index.html b/docs/6.10.0/validation-result-api/index.html index e0d3957..6c28477 100644 --- a/docs/6.10.0/validation-result-api/index.html +++ b/docs/6.10.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.10.0/whole-body-validation/index.html b/docs/6.10.0/whole-body-validation/index.html index b63c60f..65e5d4a 100644 --- a/docs/6.10.0/whole-body-validation/index.html +++ b/docs/6.10.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.10.0/wildcards/index.html b/docs/6.10.0/wildcards/index.html index 91c3529..f552a42 100644 --- a/docs/6.10.0/wildcards/index.html +++ b/docs/6.10.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check } = require('express-validator');

const app = express();
app.use(express.json());

app.post(
'/addresses',
check('addresses.*.postalCode').isPostalCode(),
check('addresses.*.number').toInt(),
(req, res) => {
// Handle the request
},
);

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" }
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.11.0/check-api/index.html b/docs/6.11.0/check-api/index.html index dabb1de..b56210a 100644 --- a/docs/6.11.0/check-api/index.html +++ b/docs/6.11.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.11.0/custom-error-messages/index.html b/docs/6.11.0/custom-error-messages/index.html index bc97a45..ed1c36e 100644 --- a/docs/6.11.0/custom-error-messages/index.html +++ b/docs/6.11.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -25,7 +25,7 @@ For example you can provide an object with multiple properties:

// check(field, withMessage) and .withMessage() work the same
check('email').isEmail().withMessage({
message: 'Not an email',
errorCode: 1,
})
- + \ No newline at end of file diff --git a/docs/6.11.0/custom-validators-sanitizers/index.html b/docs/6.11.0/custom-validators-sanitizers/index.html index 9895dd6..09bef61 100644 --- a/docs/6.11.0/custom-validators-sanitizers/index.html +++ b/docs/6.11.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
- + \ No newline at end of file diff --git a/docs/6.11.0/faq/index.html b/docs/6.11.0/faq/index.html index 0c1aa39..dab48c8 100644 --- a/docs/6.11.0/faq/index.html +++ b/docs/6.11.0/faq/index.html @@ -6,7 +6,7 @@ FAQ | express-validator - + @@ -15,7 +15,7 @@ In the second one, instead, all the elements are validated and the chain correctly returns an error.

Referenced issues:

#791, #883, #931

- + \ No newline at end of file diff --git a/docs/6.11.0/filter-api/index.html b/docs/6.11.0/filter-api/index.html index bfcc4f2..0f24387 100644 --- a/docs/6.11.0/filter-api/index.html +++ b/docs/6.11.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.11.0/index.html b/docs/6.11.0/index.html index c1d8676..8211c86 100644 --- a/docs/6.11.0/index.html +++ b/docs/6.11.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.11.0/matched-data-api/index.html b/docs/6.11.0/matched-data-api/index.html index 9ed0c9c..a344979 100644 --- a/docs/6.11.0/matched-data-api/index.html +++ b/docs/6.11.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post(
'/update-user',
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
(req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
},
);
- + \ No newline at end of file diff --git a/docs/6.11.0/migration-v5-to-v6/index.html b/docs/6.11.0/migration-v5-to-v6/index.html index 6ccda8c..f4d389d 100644 --- a/docs/6.11.0/migration-v5-to-v6/index.html +++ b/docs/6.11.0/migration-v5-to-v6/index.html @@ -6,7 +6,7 @@ Migration from v5 to v6 | express-validator - + @@ -23,7 +23,7 @@ to learn about other breaking changes.

- + \ No newline at end of file diff --git a/docs/6.11.0/running-imperatively/index.html b/docs/6.11.0/running-imperatively/index.html index 30041bb..e8b1d19 100644 --- a/docs/6.11.0/running-imperatively/index.html +++ b/docs/6.11.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain, sanitization chain, checkSchema and oneOf.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

const express = require('express');
const { validateResult, ValidationChain } = require('express-validator');
// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};
app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post(
'/update-settings',
body('email').isEmail(),
body('password').optional().isLength({ min: 6 }),
async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password)
.withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
},
);
- + \ No newline at end of file diff --git a/docs/6.11.0/sanitization-chain-api/index.html b/docs/6.11.0/sanitization-chain-api/index.html index e4809b6..c3dc58e 100644 --- a/docs/6.11.0/sanitization-chain-api/index.html +++ b/docs/6.11.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get(
'/object/:id',
param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}),
objectHandler,
);

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', body('username').default('foo'), (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'
});

.replace(values_to_replace, new_value)

Returns: the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

app.post('/', body('username').replace(['bar', 'BAR'], 'foo'), (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.11.0/sanitization/index.html b/docs/6.11.0/sanitization/index.html index e0b28a7..944b822 100644 --- a/docs/6.11.0/sanitization/index.html +++ b/docs/6.11.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.11.0/schema-validation/index.html b/docs/6.11.0/schema-validation/index.html index 3b673a6..aaaf333 100644 --- a/docs/6.11.0/schema-validation/index.html +++ b/docs/6.11.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put(
'/user/:id/password',
checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true,
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
},
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 },
},
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true,
},
}),
(req, res, next) => {
// handle the request as usual
},
);
- + \ No newline at end of file diff --git a/docs/6.11.0/validation-chain-api/index.html b/docs/6.11.0/validation-chain-api/index.html index 56c80a2..0117a8f 100644 --- a/docs/6.11.0/validation-chain-api/index.html +++ b/docs/6.11.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -32,7 +32,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.11.0/validation-result-api/index.html b/docs/6.11.0/validation-result-api/index.html index fb2538b..a577b69 100644 --- a/docs/6.11.0/validation-result-api/index.html +++ b/docs/6.11.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.11.0/whole-body-validation/index.html b/docs/6.11.0/whole-body-validation/index.html index 7d2c6a9..793e69e 100644 --- a/docs/6.11.0/whole-body-validation/index.html +++ b/docs/6.11.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.11.0/wildcards/index.html b/docs/6.11.0/wildcards/index.html index 6b797b4..af7bfe2 100644 --- a/docs/6.11.0/wildcards/index.html +++ b/docs/6.11.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check } = require('express-validator');

const app = express();
app.use(express.json());

app.post(
'/addresses',
check('addresses.*.postalCode').isPostalCode(),
check('addresses.*.number').toInt(),
(req, res) => {
// Handle the request
},
);

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" }
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.12.0/check-api/index.html b/docs/6.12.0/check-api/index.html index 060922d..4078d5e 100644 --- a/docs/6.12.0/check-api/index.html +++ b/docs/6.12.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.12.0/custom-error-messages/index.html b/docs/6.12.0/custom-error-messages/index.html index a1a2f07..31f02fc 100644 --- a/docs/6.12.0/custom-error-messages/index.html +++ b/docs/6.12.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -28,7 +28,7 @@ For example you can provide an object with multiple properties:

// check(field, withMessage) and .withMessage() work the same
check('email').isEmail().withMessage({
message: 'Not an email',
errorCode: 1,
})
- + \ No newline at end of file diff --git a/docs/6.12.0/custom-validators-sanitizers/index.html b/docs/6.12.0/custom-validators-sanitizers/index.html index f4a1861..174e578 100644 --- a/docs/6.12.0/custom-validators-sanitizers/index.html +++ b/docs/6.12.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
- + \ No newline at end of file diff --git a/docs/6.12.0/faq/index.html b/docs/6.12.0/faq/index.html index 767d53a..51bf39f 100644 --- a/docs/6.12.0/faq/index.html +++ b/docs/6.12.0/faq/index.html @@ -6,7 +6,7 @@ FAQ | express-validator - + @@ -15,7 +15,7 @@ In the second one, instead, all the elements are validated and the chain correctly returns an error.

Referenced issues:

#791, #883, #931

- + \ No newline at end of file diff --git a/docs/6.12.0/filter-api/index.html b/docs/6.12.0/filter-api/index.html index fbd5098..e7ff8b3 100644 --- a/docs/6.12.0/filter-api/index.html +++ b/docs/6.12.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.12.0/index.html b/docs/6.12.0/index.html index 8a6df6e..5db70a4 100644 --- a/docs/6.12.0/index.html +++ b/docs/6.12.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.12.0/matched-data-api/index.html b/docs/6.12.0/matched-data-api/index.html index 7699738..65efe93 100644 --- a/docs/6.12.0/matched-data-api/index.html +++ b/docs/6.12.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post(
'/update-user',
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
(req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
},
);
- + \ No newline at end of file diff --git a/docs/6.12.0/migration-v5-to-v6/index.html b/docs/6.12.0/migration-v5-to-v6/index.html index 3fb2278..672ed20 100644 --- a/docs/6.12.0/migration-v5-to-v6/index.html +++ b/docs/6.12.0/migration-v5-to-v6/index.html @@ -6,7 +6,7 @@ Migration from v5 to v6 | express-validator - + @@ -23,7 +23,7 @@ to learn about other breaking changes.

- + \ No newline at end of file diff --git a/docs/6.12.0/running-imperatively/index.html b/docs/6.12.0/running-imperatively/index.html index 2c430bc..df333ae 100644 --- a/docs/6.12.0/running-imperatively/index.html +++ b/docs/6.12.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain, sanitization chain, checkSchema and oneOf.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

const express = require('express');
const { validationResult, ValidationChain } = require('express-validator');
// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};
app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post(
'/update-settings',
body('email').isEmail(),
body('password').optional().isLength({ min: 6 }),
async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password)
.withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
},
);
- + \ No newline at end of file diff --git a/docs/6.12.0/sanitization-chain-api/index.html b/docs/6.12.0/sanitization-chain-api/index.html index b82e279..d6e6855 100644 --- a/docs/6.12.0/sanitization-chain-api/index.html +++ b/docs/6.12.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get(
'/object/:id',
param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}),
objectHandler,
);

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', body('username').default('foo'), (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'
});

.replace(values_to_replace, new_value)

Returns: the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

app.post('/', body('username').replace(['bar', 'BAR'], 'foo'), (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.12.0/sanitization/index.html b/docs/6.12.0/sanitization/index.html index 37576b3..8a9f0db 100644 --- a/docs/6.12.0/sanitization/index.html +++ b/docs/6.12.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.12.0/schema-validation/index.html b/docs/6.12.0/schema-validation/index.html index 0b9873b..f822540 100644 --- a/docs/6.12.0/schema-validation/index.html +++ b/docs/6.12.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put(
'/user/:id/password',
checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true,
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
},
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 },
},
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true,
},
}),
(req, res, next) => {
// handle the request as usual
},
);
- + \ No newline at end of file diff --git a/docs/6.12.0/validation-chain-api/index.html b/docs/6.12.0/validation-chain-api/index.html index b172adc..2685dd3 100644 --- a/docs/6.12.0/validation-chain-api/index.html +++ b/docs/6.12.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -32,7 +32,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.12.0/validation-result-api/index.html b/docs/6.12.0/validation-result-api/index.html index b14fcb5..126c34f 100644 --- a/docs/6.12.0/validation-result-api/index.html +++ b/docs/6.12.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.12.0/whole-body-validation/index.html b/docs/6.12.0/whole-body-validation/index.html index 2491a4f..6e6f4ad 100644 --- a/docs/6.12.0/whole-body-validation/index.html +++ b/docs/6.12.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.12.0/wildcards/index.html b/docs/6.12.0/wildcards/index.html index 4dade13..31b3545 100644 --- a/docs/6.12.0/wildcards/index.html +++ b/docs/6.12.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check } = require('express-validator');

const app = express();
app.use(express.json());

app.post(
'/addresses',
check('addresses.*.postalCode').isPostalCode(),
check('addresses.*.number').toInt(),
(req, res) => {
// Handle the request
},
);

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" }
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.13.0/check-api/index.html b/docs/6.13.0/check-api/index.html index 7fc3624..2c0555d 100644 --- a/docs/6.13.0/check-api/index.html +++ b/docs/6.13.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.13.0/custom-error-messages/index.html b/docs/6.13.0/custom-error-messages/index.html index 83dad8b..bd3c0b5 100644 --- a/docs/6.13.0/custom-error-messages/index.html +++ b/docs/6.13.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -28,7 +28,7 @@ For example you can provide an object with multiple properties:

// check(field, withMessage) and .withMessage() work the same
check('email').isEmail().withMessage({
message: 'Not an email',
errorCode: 1,
})
- + \ No newline at end of file diff --git a/docs/6.13.0/custom-validators-sanitizers/index.html b/docs/6.13.0/custom-validators-sanitizers/index.html index 78250a1..c3b2031 100644 --- a/docs/6.13.0/custom-validators-sanitizers/index.html +++ b/docs/6.13.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
- + \ No newline at end of file diff --git a/docs/6.13.0/faq/index.html b/docs/6.13.0/faq/index.html index 2f57e4e..c312638 100644 --- a/docs/6.13.0/faq/index.html +++ b/docs/6.13.0/faq/index.html @@ -6,7 +6,7 @@ FAQ | express-validator - + @@ -15,7 +15,7 @@ In the second one, instead, all the elements are validated and the chain correctly returns an error.

Referenced issues:

#791, #883, #931

- + \ No newline at end of file diff --git a/docs/6.13.0/filter-api/index.html b/docs/6.13.0/filter-api/index.html index 73f2e05..938e312 100644 --- a/docs/6.13.0/filter-api/index.html +++ b/docs/6.13.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.13.0/index.html b/docs/6.13.0/index.html index 3d312d8..72c020a 100644 --- a/docs/6.13.0/index.html +++ b/docs/6.13.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.13.0/matched-data-api/index.html b/docs/6.13.0/matched-data-api/index.html index f8c4287..351634d 100644 --- a/docs/6.13.0/matched-data-api/index.html +++ b/docs/6.13.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post(
'/update-user',
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
(req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
},
);
- + \ No newline at end of file diff --git a/docs/6.13.0/migration-v5-to-v6/index.html b/docs/6.13.0/migration-v5-to-v6/index.html index 62e25a4..d5f676c 100644 --- a/docs/6.13.0/migration-v5-to-v6/index.html +++ b/docs/6.13.0/migration-v5-to-v6/index.html @@ -6,7 +6,7 @@ Migration from v5 to v6 | express-validator - + @@ -23,7 +23,7 @@ to learn about other breaking changes.

- + \ No newline at end of file diff --git a/docs/6.13.0/running-imperatively/index.html b/docs/6.13.0/running-imperatively/index.html index 6179f4b..8b056ea 100644 --- a/docs/6.13.0/running-imperatively/index.html +++ b/docs/6.13.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain, sanitization chain, checkSchema and oneOf.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

const express = require('express');
const { validationResult, ValidationChain } = require('express-validator');
// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};
app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post(
'/update-settings',
body('email').isEmail(),
body('password').optional().isLength({ min: 6 }),
async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password)
.withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
},
);
- + \ No newline at end of file diff --git a/docs/6.13.0/sanitization-chain-api/index.html b/docs/6.13.0/sanitization-chain-api/index.html index 39add79..b84dd90 100644 --- a/docs/6.13.0/sanitization-chain-api/index.html +++ b/docs/6.13.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get(
'/object/:id',
param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}),
objectHandler,
);

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', body('username').default('foo'), (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'
});

.replace(values_to_replace, new_value)

Returns: the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

app.post('/', body('username').replace(['bar', 'BAR'], 'foo'), (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.13.0/sanitization/index.html b/docs/6.13.0/sanitization/index.html index aaeb5e7..c7112ed 100644 --- a/docs/6.13.0/sanitization/index.html +++ b/docs/6.13.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.13.0/schema-validation/index.html b/docs/6.13.0/schema-validation/index.html index d17f828..c5c01e9 100644 --- a/docs/6.13.0/schema-validation/index.html +++ b/docs/6.13.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put(
'/user/:id/password',
checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true,
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
},
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 },
},
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Support if functionality in schemas
someField: {
isInt: {
if: value => {
return value !== '';
},
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: {
options: 'US', // set postalCode locale here
},
},
}),
(req, res, next) => {
// handle the request as usual
},
);
- + \ No newline at end of file diff --git a/docs/6.13.0/validation-chain-api/index.html b/docs/6.13.0/validation-chain-api/index.html index 92a989e..9bf9a66 100644 --- a/docs/6.13.0/validation-chain-api/index.html +++ b/docs/6.13.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -32,7 +32,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.13.0/validation-result-api/index.html b/docs/6.13.0/validation-result-api/index.html index 04e1919..859623f 100644 --- a/docs/6.13.0/validation-result-api/index.html +++ b/docs/6.13.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.13.0/whole-body-validation/index.html b/docs/6.13.0/whole-body-validation/index.html index 47543c5..cf4b380 100644 --- a/docs/6.13.0/whole-body-validation/index.html +++ b/docs/6.13.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.13.0/wildcards/index.html b/docs/6.13.0/wildcards/index.html index 30c3477..a9af032 100644 --- a/docs/6.13.0/wildcards/index.html +++ b/docs/6.13.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check } = require('express-validator');

const app = express();
app.use(express.json());

app.post(
'/addresses',
check('addresses.*.postalCode').isPostalCode(),
check('addresses.*.number').toInt(),
(req, res) => {
// Handle the request
},
);

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" }
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.14.0/check-api/index.html b/docs/6.14.0/check-api/index.html index 7299d8c..93009ba 100644 --- a/docs/6.14.0/check-api/index.html +++ b/docs/6.14.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.14.0/custom-error-messages/index.html b/docs/6.14.0/custom-error-messages/index.html index 85452df..49c10eb 100644 --- a/docs/6.14.0/custom-error-messages/index.html +++ b/docs/6.14.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -28,7 +28,7 @@ For example you can provide an object with multiple properties:

// check(field, withMessage) and .withMessage() work the same
check('email').isEmail().withMessage({
message: 'Not an email',
errorCode: 1,
})
- + \ No newline at end of file diff --git a/docs/6.14.0/custom-validators-sanitizers/index.html b/docs/6.14.0/custom-validators-sanitizers/index.html index d976168..1f5875a 100644 --- a/docs/6.14.0/custom-validators-sanitizers/index.html +++ b/docs/6.14.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
- + \ No newline at end of file diff --git a/docs/6.14.0/faq/index.html b/docs/6.14.0/faq/index.html index 920dd40..fabd2fe 100644 --- a/docs/6.14.0/faq/index.html +++ b/docs/6.14.0/faq/index.html @@ -6,7 +6,7 @@ FAQ | express-validator - + @@ -15,7 +15,7 @@ In the second one, instead, all the elements are validated and the chain correctly returns an error.

Referenced issues:

#791, #883, #931

- + \ No newline at end of file diff --git a/docs/6.14.0/filter-api/index.html b/docs/6.14.0/filter-api/index.html index c775245..05b630e 100644 --- a/docs/6.14.0/filter-api/index.html +++ b/docs/6.14.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.14.0/index.html b/docs/6.14.0/index.html index 3fc7f02..8cf3ff9 100644 --- a/docs/6.14.0/index.html +++ b/docs/6.14.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.14.0/matched-data-api/index.html b/docs/6.14.0/matched-data-api/index.html index e0a3b03..0b53050 100644 --- a/docs/6.14.0/matched-data-api/index.html +++ b/docs/6.14.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post(
'/update-user',
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
(req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
},
);
- + \ No newline at end of file diff --git a/docs/6.14.0/migration-v5-to-v6/index.html b/docs/6.14.0/migration-v5-to-v6/index.html index 5ef04ab..28d293f 100644 --- a/docs/6.14.0/migration-v5-to-v6/index.html +++ b/docs/6.14.0/migration-v5-to-v6/index.html @@ -6,7 +6,7 @@ Migration from v5 to v6 | express-validator - + @@ -23,7 +23,7 @@ to learn about other breaking changes.

- + \ No newline at end of file diff --git a/docs/6.14.0/running-imperatively/index.html b/docs/6.14.0/running-imperatively/index.html index 302a921..88692ab 100644 --- a/docs/6.14.0/running-imperatively/index.html +++ b/docs/6.14.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain, sanitization chain, checkSchema and oneOf.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

const express = require('express');
const { validationResult, ValidationChain } = require('express-validator');
// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};
app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post(
'/update-settings',
body('email').isEmail(),
body('password').optional().isLength({ min: 6 }),
async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password)
.withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
},
);
- + \ No newline at end of file diff --git a/docs/6.14.0/sanitization-chain-api/index.html b/docs/6.14.0/sanitization-chain-api/index.html index a848dff..77088d4 100644 --- a/docs/6.14.0/sanitization-chain-api/index.html +++ b/docs/6.14.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get(
'/object/:id',
param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}),
objectHandler,
);

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', body('username').default('foo'), (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'
});

.replace(values_to_replace, new_value)

Returns: the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

app.post('/', body('username').replace(['bar', 'BAR'], 'foo'), (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar'] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.14.0/sanitization/index.html b/docs/6.14.0/sanitization/index.html index 20ec9eb..8eb49bb 100644 --- a/docs/6.14.0/sanitization/index.html +++ b/docs/6.14.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.14.0/schema-validation/index.html b/docs/6.14.0/schema-validation/index.html index a4a313e..12cdb69 100644 --- a/docs/6.14.0/schema-validation/index.html +++ b/docs/6.14.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema, validationResult } = require('express-validator');
app.put(
'/user/:id/password',
checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true,
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
},
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 },
},
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Support if functionality in schemas
someField: {
isInt: {
if: value => {
return value !== '';
},
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: {
options: 'US', // set postalCode locale here
},
},
}),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// handle the request as usual
},
);
- + \ No newline at end of file diff --git a/docs/6.14.0/validation-chain-api/index.html b/docs/6.14.0/validation-chain-api/index.html index 195e36e..dc718f3 100644 --- a/docs/6.14.0/validation-chain-api/index.html +++ b/docs/6.14.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -32,7 +32,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.14.0/validation-result-api/index.html b/docs/6.14.0/validation-result-api/index.html index 6d7b7f1..bf4272d 100644 --- a/docs/6.14.0/validation-result-api/index.html +++ b/docs/6.14.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.14.0/whole-body-validation/index.html b/docs/6.14.0/whole-body-validation/index.html index 63916b6..ff2d0db 100644 --- a/docs/6.14.0/whole-body-validation/index.html +++ b/docs/6.14.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.14.0/wildcards/index.html b/docs/6.14.0/wildcards/index.html index daaf0a7..22fa8b3 100644 --- a/docs/6.14.0/wildcards/index.html +++ b/docs/6.14.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check } = require('express-validator');

const app = express();
app.use(express.json());

app.post(
'/addresses',
check('addresses.*.postalCode').isPostalCode(),
check('addresses.*.number').toInt(),
(req, res) => {
// Handle the request
},
);

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" }
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.15.0/check-api/index.html b/docs/6.15.0/check-api/index.html index 8357a3d..d2dae98 100644 --- a/docs/6.15.0/check-api/index.html +++ b/docs/6.15.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.15.0/custom-error-messages/index.html b/docs/6.15.0/custom-error-messages/index.html index 17bc6f3..2994fbb 100644 --- a/docs/6.15.0/custom-error-messages/index.html +++ b/docs/6.15.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -28,7 +28,7 @@ For example you can provide an object with multiple properties:

// check(field, withMessage) and .withMessage() work the same
check('email').isEmail().withMessage({
message: 'Not an email',
errorCode: 1,
})
- + \ No newline at end of file diff --git a/docs/6.15.0/custom-validators-sanitizers/index.html b/docs/6.15.0/custom-validators-sanitizers/index.html index 60e5642..fdf5318 100644 --- a/docs/6.15.0/custom-validators-sanitizers/index.html +++ b/docs/6.15.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
- + \ No newline at end of file diff --git a/docs/6.15.0/faq/index.html b/docs/6.15.0/faq/index.html index a040333..767bd1c 100644 --- a/docs/6.15.0/faq/index.html +++ b/docs/6.15.0/faq/index.html @@ -6,7 +6,7 @@ FAQ | express-validator - + @@ -15,7 +15,7 @@ In the second one, instead, all the elements are validated and the chain correctly returns an error.

Referenced issues:

#791, #883, #931

- + \ No newline at end of file diff --git a/docs/6.15.0/filter-api/index.html b/docs/6.15.0/filter-api/index.html index b7a61b5..3f9c391 100644 --- a/docs/6.15.0/filter-api/index.html +++ b/docs/6.15.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.15.0/index.html b/docs/6.15.0/index.html index 6e3efdb..b8ad519 100644 --- a/docs/6.15.0/index.html +++ b/docs/6.15.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.15.0/matched-data-api/index.html b/docs/6.15.0/matched-data-api/index.html index 15c23d2..883b5f1 100644 --- a/docs/6.15.0/matched-data-api/index.html +++ b/docs/6.15.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post(
'/update-user',
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
(req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
},
);
- + \ No newline at end of file diff --git a/docs/6.15.0/migration-v5-to-v6/index.html b/docs/6.15.0/migration-v5-to-v6/index.html index 059dfb6..c6ce6ae 100644 --- a/docs/6.15.0/migration-v5-to-v6/index.html +++ b/docs/6.15.0/migration-v5-to-v6/index.html @@ -6,7 +6,7 @@ Migration from v5 to v6 | express-validator - + @@ -23,7 +23,7 @@ to learn about other breaking changes.

- + \ No newline at end of file diff --git a/docs/6.15.0/running-imperatively/index.html b/docs/6.15.0/running-imperatively/index.html index 184afde..3714eec 100644 --- a/docs/6.15.0/running-imperatively/index.html +++ b/docs/6.15.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain, sanitization chain, checkSchema and oneOf.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

const express = require('express');
const { validationResult, ValidationChain } = require('express-validator');
// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};
app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post(
'/update-settings',
body('email').isEmail(),
body('password').optional().isLength({ min: 6 }),
async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password)
.withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
},
);
- + \ No newline at end of file diff --git a/docs/6.15.0/sanitization-chain-api/index.html b/docs/6.15.0/sanitization-chain-api/index.html index 090a53c..b3dcf9d 100644 --- a/docs/6.15.0/sanitization-chain-api/index.html +++ b/docs/6.15.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get(
'/object/:id',
param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}),
objectHandler,
);

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', body('username').default('foo'), (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'
});

.replace(values_to_replace, new_value)

Returns: the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

app.post('/', body('username').replace(['bar', 'BAR'], 'foo'), (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar'] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.15.0/sanitization/index.html b/docs/6.15.0/sanitization/index.html index dfed9c7..ac3d1fc 100644 --- a/docs/6.15.0/sanitization/index.html +++ b/docs/6.15.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.15.0/schema-validation/index.html b/docs/6.15.0/schema-validation/index.html index c266303..7e0a2cd 100644 --- a/docs/6.15.0/schema-validation/index.html +++ b/docs/6.15.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema, validationResult } = require('express-validator');
app.put(
'/user/:id/password',
checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true,
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
},
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 },
},
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Support if functionality in schemas
someField: {
isInt: {
if: value => {
return value !== '';
},
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: {
options: 'US', // set postalCode locale here
},
},
}),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// handle the request as usual
},
);
- + \ No newline at end of file diff --git a/docs/6.15.0/validation-chain-api/index.html b/docs/6.15.0/validation-chain-api/index.html index 6fb4a72..fa7d278 100644 --- a/docs/6.15.0/validation-chain-api/index.html +++ b/docs/6.15.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -32,7 +32,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.15.0/validation-result-api/index.html b/docs/6.15.0/validation-result-api/index.html index 7329f1e..e46d12f 100644 --- a/docs/6.15.0/validation-result-api/index.html +++ b/docs/6.15.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.15.0/whole-body-validation/index.html b/docs/6.15.0/whole-body-validation/index.html index 92f61fb..85c610e 100644 --- a/docs/6.15.0/whole-body-validation/index.html +++ b/docs/6.15.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.15.0/wildcards/index.html b/docs/6.15.0/wildcards/index.html index 02bb5e4..d255ca3 100644 --- a/docs/6.15.0/wildcards/index.html +++ b/docs/6.15.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check } = require('express-validator');

const app = express();
app.use(express.json());

app.post(
'/addresses',
check('addresses.*.postalCode').isPostalCode(),
check('addresses.*.number').toInt(),
(req, res) => {
// Handle the request
},
);

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" }
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.2.0/check-api/index.html b/docs/6.2.0/check-api/index.html index d2032cf..e30b5e3 100644 --- a/docs/6.2.0/check-api/index.html +++ b/docs/6.2.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.2.0/custom-error-messages/index.html b/docs/6.2.0/custom-error-messages/index.html index c5afed6..519bf56 100644 --- a/docs/6.2.0/custom-error-messages/index.html +++ b/docs/6.2.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.2.0/custom-validators-sanitizers/index.html b/docs/6.2.0/custom-validators-sanitizers/index.html index e577012..4f38d1d 100644 --- a/docs/6.2.0/custom-validators-sanitizers/index.html +++ b/docs/6.2.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { sanitizeParam } = require('express-validator');

app.post('/object/:id', sanitizeParam('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.2.0/filter-api/index.html b/docs/6.2.0/filter-api/index.html index ebd87c1..8b55c89 100644 --- a/docs/6.2.0/filter-api/index.html +++ b/docs/6.2.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -14,7 +14,7 @@
Version: 6.2.0

Sanitization middlewares

These methods are all available via require('express-validator').

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.2.0/index.html b/docs/6.2.0/index.html index 8e8f35d..d66ac48 100644 --- a/docs/6.2.0/index.html +++ b/docs/6.2.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.2.0/matched-data-api/index.html b/docs/6.2.0/matched-data-api/index.html index e226f1a..95bca17 100644 --- a/docs/6.2.0/matched-data-api/index.html +++ b/docs/6.2.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.2.0/running-imperatively/index.html b/docs/6.2.0/running-imperatively/index.html index 1612d1a..f54a2b3 100644 --- a/docs/6.2.0/running-imperatively/index.html +++ b/docs/6.2.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.2.0/sanitization-chain-api/index.html b/docs/6.2.0/sanitization-chain-api/index.html index 034672a..09a66d3 100644 --- a/docs/6.2.0/sanitization-chain-api/index.html +++ b/docs/6.2.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

app.get('/object/:id', sanitizeParam('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await sanitize('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});
- + \ No newline at end of file diff --git a/docs/6.2.0/sanitization/index.html b/docs/6.2.0/sanitization/index.html index 1bf6c74..087da14 100644 --- a/docs/6.2.0/sanitization/index.html +++ b/docs/6.2.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.2.0/schema-validation/index.html b/docs/6.2.0/schema-validation/index.html index 42ea0cf..2473c19 100644 --- a/docs/6.2.0/schema-validation/index.html +++ b/docs/6.2.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntaxs looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.2.0/validation-chain-api/index.html b/docs/6.2.0/validation-chain-api/index.html index b3c7375..8a91c3d 100644 --- a/docs/6.2.0/validation-chain-api/index.html +++ b/docs/6.2.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -30,7 +30,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.2.0/validation-result-api/index.html b/docs/6.2.0/validation-result-api/index.html index 30842d5..1f79060 100644 --- a/docs/6.2.0/validation-result-api/index.html +++ b/docs/6.2.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.2.0/whole-body-validation/index.html b/docs/6.2.0/whole-body-validation/index.html index e65eef2..3beb3ac 100644 --- a/docs/6.2.0/whole-body-validation/index.html +++ b/docs/6.2.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.2.0/wildcards/index.html b/docs/6.2.0/wildcards/index.html index 6db4c2a..25ab5b6 100644 --- a/docs/6.2.0/wildcards/index.html +++ b/docs/6.2.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer number.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.3.0/check-api/index.html b/docs/6.3.0/check-api/index.html index 46e9356..28fc4d6 100644 --- a/docs/6.3.0/check-api/index.html +++ b/docs/6.3.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.3.0/custom-error-messages/index.html b/docs/6.3.0/custom-error-messages/index.html index 8780ac9..206da48 100644 --- a/docs/6.3.0/custom-error-messages/index.html +++ b/docs/6.3.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.3.0/custom-validators-sanitizers/index.html b/docs/6.3.0/custom-validators-sanitizers/index.html index 685c87e..3f9ce83 100644 --- a/docs/6.3.0/custom-validators-sanitizers/index.html +++ b/docs/6.3.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { sanitizeParam } = require('express-validator');

app.post('/object/:id', sanitizeParam('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.3.0/filter-api/index.html b/docs/6.3.0/filter-api/index.html index eaa838c..a4280d1 100644 --- a/docs/6.3.0/filter-api/index.html +++ b/docs/6.3.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -14,7 +14,7 @@
Version: 6.3.0

Sanitization middlewares

These methods are all available via require('express-validator').

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.3.0/index.html b/docs/6.3.0/index.html index 169af2e..d4fba2e 100644 --- a/docs/6.3.0/index.html +++ b/docs/6.3.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.3.0/matched-data-api/index.html b/docs/6.3.0/matched-data-api/index.html index f83c802..8f473fc 100644 --- a/docs/6.3.0/matched-data-api/index.html +++ b/docs/6.3.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.3.0/running-imperatively/index.html b/docs/6.3.0/running-imperatively/index.html index 95c8f66..035cd0e 100644 --- a/docs/6.3.0/running-imperatively/index.html +++ b/docs/6.3.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.3.0/sanitization-chain-api/index.html b/docs/6.3.0/sanitization-chain-api/index.html index d89e0dd..83266c7 100644 --- a/docs/6.3.0/sanitization-chain-api/index.html +++ b/docs/6.3.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

app.get('/object/:id', sanitizeParam('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await sanitize('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});
- + \ No newline at end of file diff --git a/docs/6.3.0/sanitization/index.html b/docs/6.3.0/sanitization/index.html index aaa4bbd..43a4f75 100644 --- a/docs/6.3.0/sanitization/index.html +++ b/docs/6.3.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.3.0/schema-validation/index.html b/docs/6.3.0/schema-validation/index.html index 65ecb2f..2f8bb7f 100644 --- a/docs/6.3.0/schema-validation/index.html +++ b/docs/6.3.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntaxs looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.3.0/validation-chain-api/index.html b/docs/6.3.0/validation-chain-api/index.html index 0cf611c..17b3c4f 100644 --- a/docs/6.3.0/validation-chain-api/index.html +++ b/docs/6.3.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -30,7 +30,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.3.0/validation-result-api/index.html b/docs/6.3.0/validation-result-api/index.html index 122a891..8275c14 100644 --- a/docs/6.3.0/validation-result-api/index.html +++ b/docs/6.3.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.3.0/whole-body-validation/index.html b/docs/6.3.0/whole-body-validation/index.html index 28c6b42..9b390a0 100644 --- a/docs/6.3.0/whole-body-validation/index.html +++ b/docs/6.3.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.3.0/wildcards/index.html b/docs/6.3.0/wildcards/index.html index a05d21e..3d6b2c1 100644 --- a/docs/6.3.0/wildcards/index.html +++ b/docs/6.3.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer number.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.4.0/check-api/index.html b/docs/6.4.0/check-api/index.html index ad64f93..d85fc56 100644 --- a/docs/6.4.0/check-api/index.html +++ b/docs/6.4.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.4.0/custom-error-messages/index.html b/docs/6.4.0/custom-error-messages/index.html index 23e1e8d..d41692c 100644 --- a/docs/6.4.0/custom-error-messages/index.html +++ b/docs/6.4.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.4.0/custom-validators-sanitizers/index.html b/docs/6.4.0/custom-validators-sanitizers/index.html index 4d14d8a..a435469 100644 --- a/docs/6.4.0/custom-validators-sanitizers/index.html +++ b/docs/6.4.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post('/object/:id', param('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.4.0/filter-api/index.html b/docs/6.4.0/filter-api/index.html index 925d918..4589e63 100644 --- a/docs/6.4.0/filter-api/index.html +++ b/docs/6.4.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.4.0/index.html b/docs/6.4.0/index.html index 8755041..025c8b9 100644 --- a/docs/6.4.0/index.html +++ b/docs/6.4.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.4.0/matched-data-api/index.html b/docs/6.4.0/matched-data-api/index.html index cc35458..640b7d9 100644 --- a/docs/6.4.0/matched-data-api/index.html +++ b/docs/6.4.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.4.0/running-imperatively/index.html b/docs/6.4.0/running-imperatively/index.html index a45cdce..e7d9272 100644 --- a/docs/6.4.0/running-imperatively/index.html +++ b/docs/6.4.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.4.0/sanitization-chain-api/index.html b/docs/6.4.0/sanitization-chain-api/index.html index 7e176e4..4b65168 100644 --- a/docs/6.4.0/sanitization-chain-api/index.html +++ b/docs/6.4.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get('/object/:id', param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});
- + \ No newline at end of file diff --git a/docs/6.4.0/sanitization/index.html b/docs/6.4.0/sanitization/index.html index 34936e5..659651c 100644 --- a/docs/6.4.0/sanitization/index.html +++ b/docs/6.4.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.4.0/schema-validation/index.html b/docs/6.4.0/schema-validation/index.html index 234dfe2..f809a04 100644 --- a/docs/6.4.0/schema-validation/index.html +++ b/docs/6.4.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.4.0/validation-chain-api/index.html b/docs/6.4.0/validation-chain-api/index.html index 3ff0f78..8d5e463 100644 --- a/docs/6.4.0/validation-chain-api/index.html +++ b/docs/6.4.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -30,7 +30,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.4.0/validation-result-api/index.html b/docs/6.4.0/validation-result-api/index.html index f269285..c0e4f2b 100644 --- a/docs/6.4.0/validation-result-api/index.html +++ b/docs/6.4.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.4.0/whole-body-validation/index.html b/docs/6.4.0/whole-body-validation/index.html index 30ed928..18925db 100644 --- a/docs/6.4.0/whole-body-validation/index.html +++ b/docs/6.4.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.4.0/wildcards/index.html b/docs/6.4.0/wildcards/index.html index ed00bd2..6c0b31f 100644 --- a/docs/6.4.0/wildcards/index.html +++ b/docs/6.4.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.5.0/check-api/index.html b/docs/6.5.0/check-api/index.html index 332d6fa..685a042 100644 --- a/docs/6.5.0/check-api/index.html +++ b/docs/6.5.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.5.0/custom-error-messages/index.html b/docs/6.5.0/custom-error-messages/index.html index 115db24..7867a88 100644 --- a/docs/6.5.0/custom-error-messages/index.html +++ b/docs/6.5.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.5.0/custom-validators-sanitizers/index.html b/docs/6.5.0/custom-validators-sanitizers/index.html index ef26186..a969772 100644 --- a/docs/6.5.0/custom-validators-sanitizers/index.html +++ b/docs/6.5.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post('/object/:id', param('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.5.0/filter-api/index.html b/docs/6.5.0/filter-api/index.html index 3a1e0ce..d182880 100644 --- a/docs/6.5.0/filter-api/index.html +++ b/docs/6.5.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.5.0/index.html b/docs/6.5.0/index.html index 937d5d7..53802bc 100644 --- a/docs/6.5.0/index.html +++ b/docs/6.5.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.5.0/matched-data-api/index.html b/docs/6.5.0/matched-data-api/index.html index 36eb6d7..6444b8e 100644 --- a/docs/6.5.0/matched-data-api/index.html +++ b/docs/6.5.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.5.0/running-imperatively/index.html b/docs/6.5.0/running-imperatively/index.html index 83e80a6..21dd861 100644 --- a/docs/6.5.0/running-imperatively/index.html +++ b/docs/6.5.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.5.0/sanitization-chain-api/index.html b/docs/6.5.0/sanitization-chain-api/index.html index ecc941c..a5d4393 100644 --- a/docs/6.5.0/sanitization-chain-api/index.html +++ b/docs/6.5.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get('/object/:id', param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});
- + \ No newline at end of file diff --git a/docs/6.5.0/sanitization/index.html b/docs/6.5.0/sanitization/index.html index a9afe39..f57a191 100644 --- a/docs/6.5.0/sanitization/index.html +++ b/docs/6.5.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.5.0/schema-validation/index.html b/docs/6.5.0/schema-validation/index.html index 31d3a71..acb07d9 100644 --- a/docs/6.5.0/schema-validation/index.html +++ b/docs/6.5.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.5.0/validation-chain-api/index.html b/docs/6.5.0/validation-chain-api/index.html index 0434cc7..66e4b1b 100644 --- a/docs/6.5.0/validation-chain-api/index.html +++ b/docs/6.5.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -30,7 +30,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.5.0/validation-result-api/index.html b/docs/6.5.0/validation-result-api/index.html index 0a5838b..f2225bf 100644 --- a/docs/6.5.0/validation-result-api/index.html +++ b/docs/6.5.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.5.0/whole-body-validation/index.html b/docs/6.5.0/whole-body-validation/index.html index 4104580..a4c4415 100644 --- a/docs/6.5.0/whole-body-validation/index.html +++ b/docs/6.5.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.5.0/wildcards/index.html b/docs/6.5.0/wildcards/index.html index 2d2c769..985f879 100644 --- a/docs/6.5.0/wildcards/index.html +++ b/docs/6.5.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.6.0/check-api/index.html b/docs/6.6.0/check-api/index.html index 4b8e6c4..65ebb4c 100644 --- a/docs/6.6.0/check-api/index.html +++ b/docs/6.6.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.6.0/custom-error-messages/index.html b/docs/6.6.0/custom-error-messages/index.html index bdd4d27..50b2627 100644 --- a/docs/6.6.0/custom-error-messages/index.html +++ b/docs/6.6.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.6.0/custom-validators-sanitizers/index.html b/docs/6.6.0/custom-validators-sanitizers/index.html index 8605744..b6067e5 100644 --- a/docs/6.6.0/custom-validators-sanitizers/index.html +++ b/docs/6.6.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post('/object/:id', param('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.6.0/filter-api/index.html b/docs/6.6.0/filter-api/index.html index d987c34..d5ee38d 100644 --- a/docs/6.6.0/filter-api/index.html +++ b/docs/6.6.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.6.0/index.html b/docs/6.6.0/index.html index cd35fd0..40c550e 100644 --- a/docs/6.6.0/index.html +++ b/docs/6.6.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.6.0/matched-data-api/index.html b/docs/6.6.0/matched-data-api/index.html index d8723cf..57bcb2e 100644 --- a/docs/6.6.0/matched-data-api/index.html +++ b/docs/6.6.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.6.0/running-imperatively/index.html b/docs/6.6.0/running-imperatively/index.html index abf5da5..008f448 100644 --- a/docs/6.6.0/running-imperatively/index.html +++ b/docs/6.6.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.6.0/sanitization-chain-api/index.html b/docs/6.6.0/sanitization-chain-api/index.html index 3f1e216..711deed 100644 --- a/docs/6.6.0/sanitization-chain-api/index.html +++ b/docs/6.6.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get('/object/:id', param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});
- + \ No newline at end of file diff --git a/docs/6.6.0/sanitization/index.html b/docs/6.6.0/sanitization/index.html index c8fc2d0..fc87240 100644 --- a/docs/6.6.0/sanitization/index.html +++ b/docs/6.6.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.6.0/schema-validation/index.html b/docs/6.6.0/schema-validation/index.html index 630cc82..d1f0732 100644 --- a/docs/6.6.0/schema-validation/index.html +++ b/docs/6.6.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.6.0/validation-chain-api/index.html b/docs/6.6.0/validation-chain-api/index.html index 4542975..49f6091 100644 --- a/docs/6.6.0/validation-chain-api/index.html +++ b/docs/6.6.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -31,7 +31,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.6.0/validation-result-api/index.html b/docs/6.6.0/validation-result-api/index.html index 8ee727d..11d0fb5 100644 --- a/docs/6.6.0/validation-result-api/index.html +++ b/docs/6.6.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.6.0/whole-body-validation/index.html b/docs/6.6.0/whole-body-validation/index.html index e5d743c..36dd4ba 100644 --- a/docs/6.6.0/whole-body-validation/index.html +++ b/docs/6.6.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.6.0/wildcards/index.html b/docs/6.6.0/wildcards/index.html index 677fc80..d8faa81 100644 --- a/docs/6.6.0/wildcards/index.html +++ b/docs/6.6.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.7.0/check-api/index.html b/docs/6.7.0/check-api/index.html index bde5700..3c7d981 100644 --- a/docs/6.7.0/check-api/index.html +++ b/docs/6.7.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.7.0/custom-error-messages/index.html b/docs/6.7.0/custom-error-messages/index.html index 6283275..13329a5 100644 --- a/docs/6.7.0/custom-error-messages/index.html +++ b/docs/6.7.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.7.0/custom-validators-sanitizers/index.html b/docs/6.7.0/custom-validators-sanitizers/index.html index 071e1b6..a78efb8 100644 --- a/docs/6.7.0/custom-validators-sanitizers/index.html +++ b/docs/6.7.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post('/object/:id', param('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.7.0/filter-api/index.html b/docs/6.7.0/filter-api/index.html index 7aebee7..7fa3883 100644 --- a/docs/6.7.0/filter-api/index.html +++ b/docs/6.7.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.7.0/index.html b/docs/6.7.0/index.html index 6464ada..deb4c2f 100644 --- a/docs/6.7.0/index.html +++ b/docs/6.7.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.7.0/matched-data-api/index.html b/docs/6.7.0/matched-data-api/index.html index 31bcda8..5ef40c9 100644 --- a/docs/6.7.0/matched-data-api/index.html +++ b/docs/6.7.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.7.0/running-imperatively/index.html b/docs/6.7.0/running-imperatively/index.html index dba843d..3324340 100644 --- a/docs/6.7.0/running-imperatively/index.html +++ b/docs/6.7.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
}
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.7.0/sanitization-chain-api/index.html b/docs/6.7.0/sanitization-chain-api/index.html index c022d02..5639757 100644 --- a/docs/6.7.0/sanitization-chain-api/index.html +++ b/docs/6.7.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get('/object/:id', param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', [body('username').default('foo')], (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'

### `.replace(values_to_replace, new_value)`
> *Returns:* the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

```js
app.post('/', [body('username').replace(['bar', 'BAR'], 'foo')], (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.7.0/sanitization/index.html b/docs/6.7.0/sanitization/index.html index e8fda64..74023e6 100644 --- a/docs/6.7.0/sanitization/index.html +++ b/docs/6.7.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.7.0/schema-validation/index.html b/docs/6.7.0/schema-validation/index.html index ef63b9a..ec3e41c 100644 --- a/docs/6.7.0/schema-validation/index.html +++ b/docs/6.7.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.7.0/validation-chain-api/index.html b/docs/6.7.0/validation-chain-api/index.html index 4fba2dd..07f109c 100644 --- a/docs/6.7.0/validation-chain-api/index.html +++ b/docs/6.7.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -31,7 +31,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.7.0/validation-result-api/index.html b/docs/6.7.0/validation-result-api/index.html index 599fbf4..fc8784f 100644 --- a/docs/6.7.0/validation-result-api/index.html +++ b/docs/6.7.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.7.0/whole-body-validation/index.html b/docs/6.7.0/whole-body-validation/index.html index 09913c0..7cba0be 100644 --- a/docs/6.7.0/whole-body-validation/index.html +++ b/docs/6.7.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.7.0/wildcards/index.html b/docs/6.7.0/wildcards/index.html index bfe6629..f45ba9a 100644 --- a/docs/6.7.0/wildcards/index.html +++ b/docs/6.7.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.8.0/check-api/index.html b/docs/6.8.0/check-api/index.html index 6d26161..4f274c4 100644 --- a/docs/6.8.0/check-api/index.html +++ b/docs/6.8.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

    Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put('/update-product', [
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.8.0/custom-error-messages/index.html b/docs/6.8.0/custom-error-messages/index.html index 1443e55..9f5651e 100644 --- a/docs/6.8.0/custom-error-messages/index.html +++ b/docs/6.8.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -24,7 +24,7 @@ This is specially useful if you use a translation library to provide tailored messages:

// check(field, withMessage) and .withMessage() work the same
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),
check('somethingElse', (value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

// oneOf is special though - it only receives the req object for now
oneOf([ someValidation, anotherValidation ], ({ req }) => {
return req.translate('validation.multiple_failures');
});
- + \ No newline at end of file diff --git a/docs/6.8.0/custom-validators-sanitizers/index.html b/docs/6.8.0/custom-validators-sanitizers/index.html index dfee88e..8dea76a 100644 --- a/docs/6.8.0/custom-validators-sanitizers/index.html +++ b/docs/6.8.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post('/object/:id', param('id').customSanitizer(value => {
return ObjectId(value);
}), (req, res) => {
// Handle the request
});
- + \ No newline at end of file diff --git a/docs/6.8.0/filter-api/index.html b/docs/6.8.0/filter-api/index.html index 230227d..0d0f62b 100644 --- a/docs/6.8.0/filter-api/index.html +++ b/docs/6.8.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

    Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

    Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put('/update-product', [
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt()
], productUpdateHandler)
- + \ No newline at end of file diff --git a/docs/6.8.0/index.html b/docs/6.8.0/index.html index 9341ce1..d90fa0f 100644 --- a/docs/6.8.0/index.html +++ b/docs/6.8.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.8.0/matched-data-api/index.html b/docs/6.8.0/matched-data-api/index.html index 9ae0084..e0cf04c 100644 --- a/docs/6.8.0/matched-data-api/index.html +++ b/docs/6.8.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post('/update-user', [
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
], (req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
});
- + \ No newline at end of file diff --git a/docs/6.8.0/running-imperatively/index.html b/docs/6.8.0/running-imperatively/index.html index 3e25a7b..307000e 100644 --- a/docs/6.8.0/running-imperatively/index.html +++ b/docs/6.8.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
}
};

app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post('/update-settings', [
body('email').isEmail(),
body('password').optional().isLength({ min: 6 })
], async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password).withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
});
- + \ No newline at end of file diff --git a/docs/6.8.0/sanitization-chain-api/index.html b/docs/6.8.0/sanitization-chain-api/index.html index c7d4098..6ab01cb 100644 --- a/docs/6.8.0/sanitization-chain-api/index.html +++ b/docs/6.8.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get('/object/:id', param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}), objectHandler)

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', [body('username').default('foo')], (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'

### `.replace(values_to_replace, new_value)`
> *Returns:* the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

```js
app.post('/', [body('username').replace(['bar', 'BAR'], 'foo')], (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.8.0/sanitization/index.html b/docs/6.8.0/sanitization/index.html index 2a69f19..68e2db5 100644 --- a/docs/6.8.0/sanitization/index.html +++ b/docs/6.8.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.8.0/schema-validation/index.html b/docs/6.8.0/schema-validation/index.html index 3b596ff..734cea7 100644 --- a/docs/6.8.0/schema-validation/index.html +++ b/docs/6.8.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put('/user/:id/password', checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
}
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
}
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 }
}
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true
}
}), (req, res, next) => {
// handle the request as usual
})
- + \ No newline at end of file diff --git a/docs/6.8.0/validation-chain-api/index.html b/docs/6.8.0/validation-chain-api/index.html index 3116919..8ae0e8c 100644 --- a/docs/6.8.0/validation-chain-api/index.html +++ b/docs/6.8.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -31,7 +31,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.8.0/validation-result-api/index.html b/docs/6.8.0/validation-result-api/index.html index 65a7007..4b6d5b4 100644 --- a/docs/6.8.0/validation-result-api/index.html +++ b/docs/6.8.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.8.0/whole-body-validation/index.html b/docs/6.8.0/whole-body-validation/index.html index 0e63e27..cabc25c 100644 --- a/docs/6.8.0/whole-body-validation/index.html +++ b/docs/6.8.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.8.0/wildcards/index.html b/docs/6.8.0/wildcards/index.html index 993a1e0..5019344 100644 --- a/docs/6.8.0/wildcards/index.html +++ b/docs/6.8.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post('/addresses', [
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt()
], (req, res) => {
// Handle the request
});

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" },
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/6.9.0/check-api/index.html b/docs/6.9.0/check-api/index.html index dcce707..9714554 100644 --- a/docs/6.9.0/check-api/index.html +++ b/docs/6.9.0/check-api/index.html @@ -6,7 +6,7 @@ Validation middlewares | express-validator - + @@ -21,7 +21,7 @@ while the execution within a chain still respects the rule defined in the check() function.

buildCheckFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, headers, params or query.

Returns: a variant of check() checking the given request locations.

Creates a variant of check() that checks the given request locations.

const { buildCheckFunction } = require('express-validator');
const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

app.put(
'/update-product',
// id must be either in req.body or req.query, and must be an UUID
checkBodyAndQuery('id').isUUID(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.9.0/custom-error-messages/index.html b/docs/6.9.0/custom-error-messages/index.html index ca5cc59..f5e2865 100644 --- a/docs/6.9.0/custom-error-messages/index.html +++ b/docs/6.9.0/custom-error-messages/index.html @@ -6,7 +6,7 @@ Custom Error Messages | express-validator - + @@ -25,7 +25,7 @@ For example you can provide an object with multiple properties:

// check(field, withMessage) and .withMessage() work the same
check('email').isEmail().withMessage({
message: 'Not an email',
errorCode: 1,
})
- + \ No newline at end of file diff --git a/docs/6.9.0/custom-validators-sanitizers/index.html b/docs/6.9.0/custom-validators-sanitizers/index.html index cbebd80..72f7324 100644 --- a/docs/6.9.0/custom-validators-sanitizers/index.html +++ b/docs/6.9.0/custom-validators-sanitizers/index.html @@ -6,7 +6,7 @@ Custom validators/sanitizers | express-validator - + @@ -22,7 +22,7 @@ moment.

Example: converting to MongoDB's ObjectID

const { param } = require('express-validator');

app.post(
'/object/:id',
param('id').customSanitizer(value => {
return ObjectId(value);
}),
(req, res) => {
// Handle the request
},
);
- + \ No newline at end of file diff --git a/docs/6.9.0/filter-api/index.html b/docs/6.9.0/filter-api/index.html index 647b9f9..9f563e0 100644 --- a/docs/6.9.0/filter-api/index.html +++ b/docs/6.9.0/filter-api/index.html @@ -6,7 +6,7 @@ Sanitization middlewares | express-validator - + @@ -16,7 +16,7 @@ They will be removed eventually.

sanitize(fields)

  • field: a string or an array of strings of field names to validate against.

Returns: a Sanitization Chain

Prefer using check() instead. This function has been deprecated.

Creates a sanitization chain for one or more fields. They may be located in any of the following request objects:

  • req.body
  • req.cookies
  • req.params
  • req.query

* req.headers is not supported at the moment.

If any of the fields are present in more than one location, then all instances of that field value will be sanitized.

sanitizeBody(fields)

Same as sanitize(fields), but only sanitizing req.body.

Prefer using body() instead. This function has been deprecated.

sanitizeCookie(fields)

Same as sanitize(fields), but only sanitizing req.cookies.

Prefer using cookie() instead. This function has been deprecated.

sanitizeParam(fields)

Same as sanitize(fields), but only sanitizing req.params.

Prefer using param() instead. This function has been deprecated.

sanitizeQuery(fields)

Same as sanitize(fields), but only sanitizing req.query.

Prefer using query() instead. This function has been deprecated.

buildSanitizeFunction(locations)

  • locations: an array of request locations to gather data from.
    May include any of body, cookies, params or query.

Returns: a variant of sanitize() sanitizing the given request locations.

Prefer using buildCheckFunction() instead. This function has been deprecated.

Creates a variant of sanitize() that sanitizes the given request locations.

const { buildSanitizeFunction } = require('express-validator');
const sanitizeBodyAndQuery = buildSanitizeFunction(['body', 'query']);

app.put(
'/update-product',
// id being either in req.body or req.query will be converted to int
sanitizeBodyAndQuery('id').toInt(),
productUpdateHandler,
);
- + \ No newline at end of file diff --git a/docs/6.9.0/index.html b/docs/6.9.0/index.html index 69394c2..936b026 100644 --- a/docs/6.9.0/index.html +++ b/docs/6.9.0/index.html @@ -6,7 +6,7 @@ Getting Started | express-validator - + @@ -19,7 +19,7 @@ You might want to continue reading about some of the more advanced features available:

- + \ No newline at end of file diff --git a/docs/6.9.0/matched-data-api/index.html b/docs/6.9.0/matched-data-api/index.html index eb23b0d..10c53ae 100644 --- a/docs/6.9.0/matched-data-api/index.html +++ b/docs/6.9.0/matched-data-api/index.html @@ -6,7 +6,7 @@ matchedData() | express-validator - + @@ -21,7 +21,7 @@ so it's useful to set them to null or an empty string.

// Suppose the request looks like this:
// req.body = { name: 'John Doe', bio: '' }

app.post(
'/update-user',
check('name').not().isEmpty(),
check('bio').optional({ checkFalsy: true }).escape(),
(req, res, next) => {
const requiredData = matchedData(req, { includeOptionals: false });
const allData = matchedData(req, { includeOptionals: true });
console.log(requiredData); // { name: 'John Doe' }
console.log(allData); // { name: 'John Doe', bio: '' }
},
);
- + \ No newline at end of file diff --git a/docs/6.9.0/running-imperatively/index.html b/docs/6.9.0/running-imperatively/index.html index 6c28636..9d22e5e 100644 --- a/docs/6.9.0/running-imperatively/index.html +++ b/docs/6.9.0/running-imperatively/index.html @@ -6,7 +6,7 @@ Running validations imperatively | express-validator - + @@ -17,7 +17,7 @@ validation chain and sanitization chains.

Check the examples below to understand how this method can help you:

Example: standardized validation error response

// can be reused by many routes

// parallel processing
const validate = validations => {
return async (req, res, next) => {
await Promise.all(validations.map(validation => validation.run(req)));

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};

// sequential processing, stops running validations chain if the previous one have failed.
const validate = validations => {
return async (req, res, next) => {
for (let validation of validations) {
const result = await validation.run(req);
if (result.errors.length) break;
}

const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}

res.status(400).json({ errors: errors.array() });
};
};
app.post('/api/create-user', validate([
body('email').isEmail(),
body('password').isLength({ min: 6 })
]), async (req, res, next) => {
// request is guaranteed to not have any validation errors.
const user = await User.create({ ... });
});

Example: validating with a condition

app.post(
'/update-settings',
body('email').isEmail(),
body('password').optional().isLength({ min: 6 }),
async (req, res, next) => {
// if a password has been provided, then a confirmation must also be provided.
if (req.body.password) {
await body('passwordConfirmation')
.equals(req.body.password)
.withMessage('passwords do not match')
.run(req);
}

// Check the validation errors, and update the user's settings.
},
);
- + \ No newline at end of file diff --git a/docs/6.9.0/sanitization-chain-api/index.html b/docs/6.9.0/sanitization-chain-api/index.html index 0a2847e..7757b08 100644 --- a/docs/6.9.0/sanitization-chain-api/index.html +++ b/docs/6.9.0/sanitization-chain-api/index.html @@ -6,7 +6,7 @@ Sanitization Chain API | express-validator - + @@ -18,7 +18,7 @@ Receives the value of the field being sanitized, as well as the express request, the location and the field path.

Returns: the current sanitization chain instance

Adds a custom sanitizer to the current sanitization chain. It must synchronously return the new value.

Example:

const { param } = require('express-validator');
app.get(
'/object/:id',
param('id').customSanitizer((value, { req }) => {
return req.query.type === 'user' ? ObjectId(value) : Number(value);
}),
objectHandler,
);

.default(default_value)

Returns: the current sanitization chain instance

Replaces the current value with a default one if the current value is included in ['', null, undefined, NaN].

app.post('/', body('username').default('foo'), (req, res, next) => {
// 'bar' => 'bar'
// '' => 'foo'
// undefined => 'foo'
// null => 'foo'
// NaN => 'foo'
});

.replace(values_to_replace, new_value)

Returns: the current sanitization chain instance

Replaces the current value with a new one if the current value is included in a given Array.

app.post('/', body('username').replace(['bar', 'BAR'], 'foo'), (req, res, next) => {
// 'bar_' => 'bar_'
// 'bar' => 'foo'
// 'BAR' => 'foo'
console.log(req.body.username);
});

.run(req)

Returns: a promise that resolves when the sanitization chain ran.

Runs the current sanitization chain in an imperative way.

const { check } = require('express-validator');
app.post('/create-post', async (req, res, next) => {
// BEFORE:
// req.body.content = ' hey your forum is amazing! <script>runEvilFunction();</script> ';
await check('content').escape().trim().run(req);

// AFTER:
// req.body.content = 'hey your forum is amazing! &lt;script&gt;runEvilFunction();&lt;/script&gt;';
});

.toArray()

Returns: the current sanitization chain instance

Converts the value to an array. undefined will result in an empty array.

app.post('/', [body('checkboxes').toArray()], (req, res, next) => {
// ['foo', 'bar] => ['foo', 'bar']
// 'foo' => ['foo']
// undefined => []
console.log(req.body.checkboxes);
});

.toLowerCase()

Returns: the current sanitization chain instance

Converts the value to lower case. Non string value will return itself.

app.post('/', [body('username').toLowerCase()], (req, res, next) => {
// 'Foo' => 'foo'
// undefined => undefined
// null => null
console.log(req.body.username);
});

.toUpperCase()

Returns: the current sanitization chain instance

Converts the value to upper case. Non string value will return itself.

app.post('/', [body('username').toUpperCase()], (req, res, next) => {
// 'Foo' => 'FOO'
// undefined => undefined
// null => null
console.log(req.body.username);
});
- + \ No newline at end of file diff --git a/docs/6.9.0/sanitization/index.html b/docs/6.9.0/sanitization/index.html index e3d6475..d70e76b 100644 --- a/docs/6.9.0/sanitization/index.html +++ b/docs/6.9.0/sanitization/index.html @@ -6,7 +6,7 @@ Sanitization | express-validator - + @@ -22,7 +22,7 @@ its value will be Hello world :&gt;).

- + \ No newline at end of file diff --git a/docs/6.9.0/schema-validation/index.html b/docs/6.9.0/schema-validation/index.html index beea380..8d74384 100644 --- a/docs/6.9.0/schema-validation/index.html +++ b/docs/6.9.0/schema-validation/index.html @@ -6,7 +6,7 @@ Schema Validation | express-validator - + @@ -16,7 +16,7 @@ the error messages, locations and validations/sanitizations.

Its syntax looks like this:

const { checkSchema } = require('express-validator');
app.put(
'/user/:id/password',
checkSchema({
id: {
// The location of the field, can be one or more of body, cookies, headers, params or query.
// If omitted, all request locations will be checked
in: ['params', 'query'],
errorMessage: 'ID is wrong',
isInt: true,
// Sanitizers can go here as well
toInt: true,
},
myCustomField: {
// Custom validators
custom: {
options: (value, { req, location, path }) => {
return value + req.body.foo + location + path;
},
},
// and sanitizers
customSanitizer: {
options: (value, { req, location, path }) => {
let sanitizedValue;

if (req.body.foo && location && path) {
sanitizedValue = parseInt(value);
} else {
sanitizedValue = 0;
}

return sanitizedValue;
},
},
},
password: {
isLength: {
errorMessage: 'Password should be at least 7 chars long',
// Multiple options would be expressed as an array
options: { min: 7 },
},
},
firstName: {
isUppercase: {
// To negate a validator
negated: true,
},
rtrim: {
// Options as an array
options: [' -'],
},
},
// Support bail functionality in schemas
email: {
isEmail: {
bail: true,
},
},
// Wildcards/dots for nested fields work as well
'addresses.*.postalCode': {
// Make this field optional when undefined or null
optional: { options: { nullable: true } },
isPostalCode: true,
},
}),
(req, res, next) => {
// handle the request as usual
},
);
- + \ No newline at end of file diff --git a/docs/6.9.0/validation-chain-api/index.html b/docs/6.9.0/validation-chain-api/index.html index 571a7a1..8f9a69b 100644 --- a/docs/6.9.0/validation-chain-api/index.html +++ b/docs/6.9.0/validation-chain-api/index.html @@ -6,7 +6,7 @@ Validation Chain API | express-validator - + @@ -31,7 +31,7 @@ This will have precedence over errors thrown by a custom validator.

To build dynamic messages, see also Dynamic Messages.

- + \ No newline at end of file diff --git a/docs/6.9.0/validation-result-api/index.html b/docs/6.9.0/validation-result-api/index.html index 2f0ce8a..9801395 100644 --- a/docs/6.9.0/validation-result-api/index.html +++ b/docs/6.9.0/validation-result-api/index.html @@ -6,7 +6,7 @@ validationResult() | express-validator - + @@ -19,7 +19,7 @@ decorated with the same validation result API.

try {
validationResult(req).throw();
// Oh look at ma' success! All validations passed!
} catch (err) {
console.log(err.mapped()); // Oh noes!
}
- + \ No newline at end of file diff --git a/docs/6.9.0/whole-body-validation/index.html b/docs/6.9.0/whole-body-validation/index.html index edbb938..c1a2186 100644 --- a/docs/6.9.0/whole-body-validation/index.html +++ b/docs/6.9.0/whole-body-validation/index.html @@ -6,7 +6,7 @@ Whole Body Validation | express-validator - + @@ -15,7 +15,7 @@ That's why you can omit the field to validate, and check req.body directly:

const bodyParser = require('body-parser');
const express = require('express');
const { body } = require('express-validator');

const app = express();

// Will handle text/plain requests
app.use(bodyParser.text());

app.post('/recover-password', body().isEmail(), (req, res) => {
// Assume the validity of the request was already checked
User.recoverPassword(req.body).then(() => {
res.send('Password recovered!');
});
});

This setup should be able to handle the following request:

POST /recover-password HTTP/1.1
Host: localhost:3000
Content-Type: text/plain

my@email.com
- + \ No newline at end of file diff --git a/docs/6.9.0/wildcards/index.html b/docs/6.9.0/wildcards/index.html index cdac937..dc9cd15 100644 --- a/docs/6.9.0/wildcards/index.html +++ b/docs/6.9.0/wildcards/index.html @@ -6,7 +6,7 @@ Wildcards | express-validator - + @@ -16,7 +16,7 @@ and that the number of each address is sanitized as an integer.

We can do this with the following code:

const express = require('express');
const { check, sanitize } = require('express-validator');

const app = express();
app.use(express.json());

app.post(
'/addresses',
check('addresses.*.postalCode').isPostalCode(),
sanitize('addresses.*.number').toInt(),
(req, res) => {
// Handle the request
},
);

This will handle cases where you send an array of addresses:

{
"addresses": [
{ "postalCode": "2010", "number": "500" },
{ "postalCode": "", "number": "501" }
]
}

...or even cases where you want a predefined set of addresses:

{
"addresses": {
"home": { "postalCode": "", "number": "501" },
"work": { "postalCode": "2010", "number": "500" }
}
}
- + \ No newline at end of file diff --git a/docs/api/check-exact/index.html b/docs/api/check-exact/index.html index b9bd079..ba1d32e 100644 --- a/docs/api/check-exact/index.html +++ b/docs/api/check-exact/index.html @@ -6,7 +6,7 @@ checkExact | express-validator - + @@ -35,7 +35,7 @@ you can also run it manually, if you wish.

app.post(
'/signup',
body('email').isEmail(),
body('password').isLength({ min: 8 }),
async (req, res) => {
const result = await checkExact().run(req);
if (result.isEmpty()) {
console.log('No unknown fields in the request');
}
},
);
tip

UnknownFieldMessageFactory

type UnknownFieldMessageFactory = (
unknownFields: UnknownFieldInstance[],
opts: { req: Request },
) => any;

The message factory type used when the checkExact() message option is a function.

checkExact([body('name').notEmpty(), body('email').isEmail()], {
message: fields => {
const [field] = fields;
return `Unknown field ${field.path} in ${field.location} with value ${field.value}`;
},
});
- + \ No newline at end of file diff --git a/docs/api/check-schema/index.html b/docs/api/check-schema/index.html index b56e3ba..1322c99 100644 --- a/docs/api/check-schema/index.html +++ b/docs/api/check-schema/index.html @@ -6,7 +6,7 @@ checkSchema | express-validator - + @@ -34,7 +34,7 @@ Different schemas can make use of the same custom name without clash.

- + \ No newline at end of file diff --git a/docs/api/check/index.html b/docs/api/check/index.html index 72120dd..f879439 100644 --- a/docs/api/check/index.html +++ b/docs/api/check/index.html @@ -6,7 +6,7 @@ check | express-validator - + @@ -15,10 +15,10 @@ It gives you access to all of the built-in validators, sanitizers, and a bunch of other utility functions to shape the validation just the way you need.

check()

import { check } from 'express-validator';
check(fields?: string | string[], message?: any): ValidationChain

Parameters:

NameDescription
fieldsOne or more field names to select. If omitted, selects the whole request location.
messageWhich error message to use when a validator doesn't specify one.

Creates a validation chain for one or more fields. Fields are selected from any of the following request locations:

  • req.body
  • req.cookies
  • req.headers
  • req.query
  • req.params

If any of the fields is present in more than one location, then all instances of that field value -are processed by the validation chain.

body()

import { body } from 'express-validator';
body(fields?: string | string[], message?: any): ValidationChain

Same as check(), but only checking req.body.

cookies()

import { cookies } from 'express-validator';
cookies(fields?: string | string[], message?: any): ValidationChain

Same as check(), but only checking req.cookies.

headers()

import { headers } from 'express-validator';
headers(fields?: string | string[], message?: any): ValidationChain

Same as check(), but only checking req.headers.

params()

import { params } from 'express-validator';
params(fields?: string | string[], message?: any): ValidationChain

Same as check(), but only checking req.params.

query()

import { query } from 'express-validator';
query(fields?: string | string[], message?: any): ValidationChain

Same as check(), but only checking req.query.