diff --git a/README.md b/README.md index 7c2a38a..38f858d 100644 --- a/README.md +++ b/README.md @@ -525,6 +525,18 @@ check({ roles: "user" }); // Valid // After both validation: roles = ["user"] ``` +**Example for `filterUndefined`:** + +```js +const schema = { + roles: { type: "array", filterUndefined: true } +} +const check = v.compile(schema); + +check({ roles: ["user", undefined, "employer"] }); // Valid +// After validation: roles = ["user", "employer"] +``` + ### Properties Property | Default | Description -------- | -------- | ----------- @@ -537,6 +549,7 @@ Property | Default | Description `enum` | `null` | Every element must be an element of the `enum` array. `items` | `null` | Schema for array items. `convert`| `null` | Wrap value into array if different type provided +`filterUndefined`| `null` | Filter undefined value in resulted array. ## `boolean` This is a `Boolean` validator. diff --git a/lib/rules/array.js b/lib/rules/array.js index bf64945..ce7eae0 100644 --- a/lib/rules/array.js +++ b/lib/rules/array.js @@ -84,9 +84,12 @@ module.exports = function ({ schema, messages }, path, context) { `); } + src.push(` + var arr = value; + `); + if (schema.items != null) { src.push(` - var arr = value; var parentField = field; for (var i = 0; i < arr.length; i++) { value = arr[i]; @@ -99,15 +102,18 @@ module.exports = function ({ schema, messages }, path, context) { src.push(this.compileRule(rule, context, itemPath, innerSource, "arr[i]")); src.push(` } - `); + `); + } + + if (schema.filterUndefined === true) { src.push(` + arr = arr.filter(x => x !== undefined); + `); + } + + src.push(` return arr; `); - } else { - src.push(` - return value; - `); - } return { sanitized,