Skip to content

Commit 7c6729a

Browse files
Tomo Wangfengmk2
authored andcommitted
feat(array): support max and min in array check (#22)
1 parent e4482f6 commit 7c6729a

3 files changed

Lines changed: 22 additions & 1 deletion

File tree

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,10 +157,12 @@ If type is `object`, there has one addition rule:
157157

158158
#### array
159159

160-
If type is `array`, there has tow addition rule:
160+
If type is `array`, there has four addition rule:
161161

162162
- `itemType` - The type of every item in this array.
163163
- `rule` - An object that validate the items of the array. Only work with `itemType`.
164+
- `max` - The maximun length of the array.
165+
- `min` - The minimun lenght of the array.
164166

165167
#### abbr
166168

index.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,13 @@ function checkArray(rule, value) {
461461
return this.t('should be an array');
462462
}
463463

464+
if (rule.hasOwnProperty('max') && value.length > rule.max) {
465+
return this.t('length should smaller than %s', rule.max);
466+
}
467+
if (rule.hasOwnProperty('min') && value.length < rule.min) {
468+
return this.t('length should bigger than %s', rule.min);
469+
}
470+
464471
if (!rule.itemType) {
465472
return;
466473
}

test/index.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -543,6 +543,18 @@ describe('parameter', function () {
543543
}).should.throw('rule type must be one of number, int, integer, string, id, date, dateTime, datetime, boolean, bool, array, object, enum, email, password, url, but the following type was passed: invalid');
544544
});
545545

546+
it('should check max error', function () {
547+
var value = {array: [0, 1, 2, 3, 4]};
548+
var rule = {array: {type: 'array', itemType: 'int', max: 4, min: 1}};
549+
parameter.validate(rule, value)[0].message.should.equal('length should smaller than 4');
550+
});
551+
552+
it('should check min error', function () {
553+
var value = {array: [0, 1, 2, 3, 4]};
554+
var rule = {array: {type: 'array', itemType: 'int', max: 100, min: 10}};
555+
parameter.validate(rule, value)[0].message.should.equal('length should bigger than 10');
556+
});
557+
546558
it('should check itemType=object error', function () {
547559
var value = {
548560
array: [{

0 commit comments

Comments
 (0)