2020-06-03 15:49:04 +00:00
|
|
|
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
|
2020-06-10 13:32:50 +00:00
|
|
|
this._regexp = null
|
2020-06-03 15:49:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
|
|
|
}
|
|
|
|
|
2020-06-10 13:32:50 +00:00
|
|
|
/**
|
|
|
|
* 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
|
|
|
|
}
|
|
|
|
|
2020-06-03 15:49:04 +00:00
|
|
|
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}`
|
2020-06-10 13:32:50 +00:00
|
|
|
if (this._regexp !== null && !this._regexp.test(value)) return `value pattern not match ${this._regexp.toString()}`
|
2020-06-03 15:49:04 +00:00
|
|
|
return null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = TypeString
|