Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------- | -------- | -----------
Expand All @@ -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.
Expand Down
20 changes: 13 additions & 7 deletions lib/rules/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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,
Expand Down