diff --git a/src/array.js b/src/array.js index 16cb9a00c..f52b10853 100644 --- a/src/array.js +++ b/src/array.js @@ -15,7 +15,7 @@ let hasLength = value => !isAbsent(value) && value.length > 0; module.exports = ArraySchema function ArraySchema(){ - if ( !(this instanceof ArraySchema)) + if (!(this instanceof ArraySchema)) return new ArraySchema() MixedSchema.call(this, { type: 'array'}) @@ -27,11 +27,6 @@ function ArraySchema(){ values = JSON.parse(values) } catch (err){ values = null } - if (Array.isArray(values)) - return this._subType - ? values.map(this._subType.cast, this._subType) - : values - return this.isType(values) ? values : null }) }) @@ -43,6 +38,16 @@ inherits(ArraySchema, MixedSchema, { return Array.isArray(v) }, + _cast(_value, _opts) { + var value = MixedSchema.prototype._cast.call(this, _value) + + //should ignore nulls here + if (!this._typeCheck(value) || !this._subType) + return value; + + return value.map(v => this._subType.cast(v, _opts)) + }, + _validate(_value, _opts, _state){ var errors = [] , context, subType, schema, endEarly, recursive; diff --git a/test/array.js b/test/array.js index 8fa302097..6b5d3390b 100644 --- a/test/array.js +++ b/test/array.js @@ -16,7 +16,7 @@ describe('Array types', function(){ it('should CAST correctly', function(){ var inst = array(); - inst.cast('[2,3,5,6]').should.eql([2,3,5,6]) + inst.cast('[2,3,5,6]').should.eql([2, 3, 5, 6]) inst.cast(['4', 5, false]).should.eql(['4', 5, false]) @@ -53,6 +53,19 @@ describe('Array types', function(){ inst.nullable().isType(null).should.equal(true) }) + it('should cast children', function(){ + array() + .of(number()) + .cast(['1', '3']).should.eql([1, 3]) + }) + + it('should pass options to children', function(){ + array() + .of(object({ name: string() })) + .cast([{ id: 1, name: 'john' }], { stripUnknown: true }) + .should.eql([{name: 'john'}]) + }) + it('should VALIDATE correctly', function(){ var inst = array().required().of(number().max(5))