Skip to content

Commit

Permalink
Merge pull request #3 from hckrnews/feature/validate-input-array
Browse files Browse the repository at this point in the history
Validate an array of items
  • Loading branch information
w3nl committed Feb 19, 2020
2 parents d8bf1bc + 3460fe2 commit 2dd1ee8
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 5 deletions.
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,32 @@ const personObj = {
}
```

You can also validate an array of items:
```javascript
const persons = [
{
name: "James",
age: 25,
siblings: ["Johnnathan"],
metaData: {},
active: true,
address: {
street: "Streetname",
number: 1,
postalCode: "1234AB",
city: "City",
country: "Somewehere"
},
companies: [
{ name: "Example company 1", website: "https://hckr.news" }
{ name: "Example company 2" }
]
}
];

validator.validateAll(persons);
```

Available types:
* string
* array
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hckrnews/validator",
"version": "1.1.1",
"version": "1.2.0",
"description": "Object validator",
"main": "src/validator.js",
"files": [
Expand Down
15 changes: 15 additions & 0 deletions src/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ export class Validator {
this.schema = schema;
}

/**
* Validate the an array of items.
*
* @param {array} input
*
* @return {boolean}
*/
validateAll(input) {
if (input.constructor != Array || input.length < 1) {
return false;
}

return input.every(item => this.validate(item));
}

/**
* Validate the input.
*
Expand Down
29 changes: 26 additions & 3 deletions tests/unit/validator.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,31 @@ const testCaseArrays = [
],
schema: personSchema,
expectedValue: false
},
{
description: "Input isnt an array",
input: {
name: "James",
age: 25,
siblings: ["Johnnathan"],
active: true,
address: {
street: "Streetname",
number: 1,
postalCode: "1234AB",
city: "City",
country: "Somewehere"
},
companies: [{ name: "Example 1" }, { name: "Example 2" }]
},
schema: personSchema,
expectedValue: false
},
{
description: "Input is an empty array",
input: [],
schema: personSchema,
expectedValue: false
}
];

Expand All @@ -188,9 +213,7 @@ describe.each(testCaseArrays)(
it(description, () => {
const validator = new Validator(schema);

expect(input.every(item => validator.validate(item))).toEqual(
expectedValue
);
expect(validator.validateAll(input)).toEqual(expectedValue);
});
}
);

0 comments on commit 2dd1ee8

Please sign in to comment.