Compare commits

...

2 Commits

Author SHA1 Message Date
Jay
4ae4427e8e Merge pull request '[feat] add array validate contains type' (#16) from feature/add-array-contains-type-validate into develop
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #16
2020-07-04 14:32:15 +00:00
Jay
a0e117c540 [feat] add array validate contains type
All checks were successful
continuous-integration/drone/push Build is passing
2020-07-04 14:30:08 +00:00
2 changed files with 40 additions and 0 deletions

View File

@ -1,5 +1,6 @@
const Base = require('./base.js')
const util = require('util')
const validate = require('../validate.js')
class TypeArray extends Base {
constructor () {
@ -8,6 +9,10 @@ class TypeArray extends Base {
this._empty = false
this._min = null
this._max = null
/**
* @type {Base[]}
*/
this._itemTypes = []
}
/**
@ -30,6 +35,11 @@ class TypeArray extends Base {
return this
}
items (...args) {
this._itemTypes.push(...args)
return this
}
/**
* set max length
* @param {number} num
@ -50,6 +60,23 @@ class TypeArray extends Base {
if (!this._empty && value.length === 0) return `not allow empty`
if (this._min !== null && value.length < this._min) return `value length < ${this._min}`
if (this._max !== null && value.length > this._max) return `value length > ${this._max}`
for (const item of value) {
let verified = false
let fail = ''
for (const type of this._itemTypes) {
const result = type.validate(item)
if (result) {
fail = result
} else {
verified = true
fail = ''
break
}
}
if (!verified || fail) return fail || `item type not match`
}
return null
}
}

View File

@ -1,5 +1,7 @@
/* eslint-disable no-undef */
const TypeArray = require('./array.js')
const TypeString = require('./string.js')
const TypeObject = require('./object.js')
describe('test validate schema type array', () => {
function throwFunc (val) {
@ -59,4 +61,15 @@ describe('test validate schema type array', () => {
expect(throwFunc(arr.validate([1, 2, 3]))).toThrow()
})
it('test array contains value', async () => {
const arr = new TypeArray().items(new TypeString())
expect(throwFunc(arr.validate([1, 2, 3]))).toThrow()
throwFunc(arr.validate(['asd']))
const arr2 = new TypeArray().items(new TypeString(), new TypeObject())
expect(throwFunc(arr2.validate([123, true]))).toThrow()
throwFunc(arr2.validate(['asd', '33', {}]))
})
})