validator/types/number.js

47 lines
1.3 KiB
JavaScript

const Base = require('./base.js')
const util = require('util')
class TypeNumber extends Base {
constructor () {
super()
this._type = 'number'
this._min = null
this._max = null
}
/**
* set min value
* @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 value
* @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
}
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}`
const v = parseFloat(value)
if (this._min !== null && v < this._min) return `value < ${this._min}`
if (this._max !== null && v > this._max) return `value > ${this._max}`
return null
}
}
module.exports = TypeNumber