Skip to content

Commit

Permalink
add length, minLength, maxLength to array
Browse files Browse the repository at this point in the history
  • Loading branch information
SomeoneWeird committed Feb 19, 2015
1 parent 738d352 commit e24e2d3
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ A string validator that matches a regex (regex can optionally be passed in as a
s.String({ regex: /h[ae]llo world/ });
```

### s.Array { opt: false }
### s.Array { opt: false, length: null, minLength: null, maxLength: null }

An array validator which can only contain Dates.
```javascript
Expand Down
38 changes: 38 additions & 0 deletions test/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,42 @@ describe("Array validator", function() {
assert.deepEqual(schema.validate(messyArray), messyArray);
});

it("should accept length option", function() {

var schema = s.Array({ length: 5 }, [ s.Number() ]);

assert.throws(function() {
schema.validate([ 1, 2, 3, 4 ]);
});

assert.deepEqual(schema.validate([ 1, 2, 3, 4, 5 ]), [ 1, 2, 3, 4, 5 ]);

});

it("should accept minLength option", function() {

var schema = s.Array({ minLength: 3 }, [ s.Number() ]);

assert.throws(function() {
schema.validate([ 1, 2 ]);
});

assert.deepEqual(schema.validate([ 1, 2, 3 ]), [ 1, 2, 3 ]);
assert.deepEqual(schema.validate([ 1, 2, 3, 4, 5, 6, 7 ]), [ 1, 2, 3, 4, 5, 6, 7 ]);

});

it("should accept maxLength option", function() {

var schema = s.Array({ maxLength: 3 }, [ s.Number() ]);

assert.throws(function() {
schema.validate([ 1, 2, 3, 4 ]);
});

assert.deepEqual(schema.validate([ 1 ]), [ 1 ]);
assert.deepEqual(schema.validate([ 1, 2, 3 ]), [ 1, 2, 3 ]);

});

});
12 changes: 12 additions & 0 deletions validators/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ function arrayParser(args, childValidators, data, key) {
throw new Error("required Array");
}

if(typeof args.length == 'number' && data.length !== args.length) {
throw new Error("required array with " + args.length + " items, got: " + data.length);
}

if(typeof args.minLength == 'number' && data.length < args.minLength) {
throw new Error("required array wtith minimum " + args.length + " items, got: " + data.length);
}

if(typeof args.maxLength == 'number' && data.length > args.maxLength) {
throw new Error("required array with maximum " + args.length + " items, got: " + data.length);
}

for(var i = 0; i < data.length; i++) {

var val = data[i];
Expand Down

0 comments on commit e24e2d3

Please sign in to comment.