validator/types/string.js

60 lines
1.5 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
}
/**
* 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
}
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}`
return null
}
}
module.exports = TypeString