validator/types/string.js
Jay 46b19757bd
All checks were successful
continuous-integration/drone/push Build is passing
[feat] add string type pattern check, add object child check
2020-06-10 13:32:50 +00:00

73 lines
1.9 KiB
JavaScript

const Base = require('./base.js')
const util = require('util')
/**
* @implements {Base}
*/
class TypeString extends Base {
constructor () {
super()
this._type = 'string'
this._max = null
this._min = null
this._empty = false
this._regexp = null
}
/**
* set min length
* @param {number} num
*/
min (num) {
if (!isFinite(num) || num === true || num === false) throw new Error('input wrong')
if (this._max !== null && this._max <= num) throw new Error(`num >= ${this._max}`)
this._min = parseFloat(num)
return this
}
/**
* set max length
* @param {number} num
*/
max (num) {
if (!isFinite(num) || num === true || num === false) throw new Error('input wrong')
if (this._min !== null && this._min >= num) throw new Error(`num <= ${this._min}`)
this._max = parseFloat(num)
return this
}
/**
* set allow empty
*/
empty () {
this._empty = true
return this
}
/**
* set test pattern with regexp
* @param {RegExp} regexp
*/
pattern (regexp) {
if (!(regexp instanceof RegExp)) throw new Error('input wrong')
if (this._regexp !== null) throw new Error('regexp pattern already exist')
this._regexp = regexp
return this
}
validate (value) {
if (value === undefined && this._required) return `required`
if (value === undefined) return null
/* eslint-disable-next-line */
if (typeof value !== this._type) return `${util.inspect(value, false, null)} type not ${this._type}`
if (!this._empty && !value) return `value empty`
const len = value.length
if (this._min !== null && len < this._min) return `value length < ${this._min}`
if (this._max !== null && len > this._max) return `value length > ${this._max}`
if (this._regexp !== null && !this._regexp.test(value)) return `value pattern not match ${this._regexp.toString()}`
return null
}
}
module.exports = TypeString