Skip to content

Commit

Permalink
validate whether array has only unique items (#89)
Browse files Browse the repository at this point in the history
* validate whether array has only unique items

* add example property, group with bool opts
  • Loading branch information
t3h2mas authored and talyssonoc committed Sep 16, 2019
1 parent 8c958d4 commit 8ada263
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
4 changes: 3 additions & 1 deletion docs/validation/array-validations.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

- `required`: can't be undefined (default: `false`)
- `sparse`: can have undefined items (default: `true`)
- `unique`: can't have duplicate items (default: `false`)
- `minLength`: minimum quantity of items
- `maxLength`: maximum quantity of items
- `exactLength`: exact quantity of items
Expand All @@ -13,7 +14,8 @@ const Group = attributes({
itemType: String,
minLength: 2,
maxLength: 5,
sparse: false
sparse: false,
unique: true
},
leaders: {
type: Array,
Expand Down
2 changes: 2 additions & 0 deletions src/validation/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const joiMappings = [
['minLength', 'min', true],
['maxLength', 'max', true],
['exactLength', 'length', true],
['unique', 'unique']

];

module.exports = function arrayValidation(typeDescriptor, itemTypeDescriptor) {
Expand Down
37 changes: 37 additions & 0 deletions test/unit/validation/array.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -377,5 +377,42 @@ describe('validation', () => {
});
});
});
describe('unique', () => {
var User;

beforeEach(() => {
User = attributes({
books: {
type: Array,
itemType: String,
unique: true
}
})(class User {});
});
context('when array is unique', () => {
it('is valid', () => {
const user = new User({
books: [
'The Gunslinger',
'The Drawing of the Three'
]
});

assertValid(user);
});
});
context('when array is not unique', () => {
it('is not valid and has errors set', () => {
const user = new User({
books: [
'The Wastelands',
'The Wastelands'
]
});

assertInvalid(user, 'books.1');
});
});
});
});
});

0 comments on commit 8ada263

Please sign in to comment.