UNPKG

aptx-validator

Version:

轻量易用的 Node.js + Typescript 参数校验库

109 lines (108 loc) 2.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_ERROR_TEXT = exports.isEmptyValue = void 0; class Utils { /* General */ number() { return (v) => Object.prototype.toString.call(v) === '[object Number]'; } isNaN() { return (v) => Number.isNaN(v); } boolean() { return (v) => Object.prototype.toString.call(v) === '[object Boolean]'; } string() { return (v) => Object.prototype.toString.call(v) === '[object String]'; } array() { return (v) => Object.prototype.toString.call(v) === '[object Array]'; } object() { return (v) => Object.prototype.toString.call(v) === '[object Object]'; } bigInt() { return (v) => Object.prototype.toString.call(v) === '[object BigInt]'; } oneof(arr) { return (v) => arr.includes(v); } /* Number Methods */ min(min) { return (v) => v >= min; } max(max) { return (v) => v <= max; } int() { return (v) => v % 1 === 0; } positive() { return (v) => v > 0; } negative() { return (v) => v < 0; } id() { return (v) => v > 0 && v % 1 === 0; } /* String Methods */ minLength(min) { return (v) => v.length >= min; } maxLength(max) { return (v) => v.length <= max; } toFixed(length) { if (length <= 0 || length % 1 !== 0) { throw new Error('Tofixed value should be greater than 0.'); } return (v) => { const n = v.toString(); const arr = n.split('.'); if (arr.length <= 1) return false; else return arr[1].length === length; }; } numeric() { return (v) => /^\d+$/.test(v); } useRE(re) { return (v) => re.test(v); } email(emailRE) { return (v) => emailRE ? emailRE.test(v) : /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/.test(v); } phone(phoneRE) { // TODO implement this fuction return (v) => phoneRE ? phoneRE.test(v) : /^[1][3,4,5,7,8][0-9]{9}$/.test(v); } date(datePatterns) { // TODO implement this fuction return (v) => true; } booleanStr() { return (v) => v === 'false' || v === 'true'; } resetFunction(name, fn) { if (name != 'resetFunction' && this[name]) { this[name] = fn; } } } /** * @param {*} v * @returns {boolean} true if the value is undefined or null or NaN */ const isEmptyValue = (v) => v === null || v === undefined || (typeof v === 'number' && isNaN(v)); exports.isEmptyValue = isEmptyValue; exports.default = new Utils(); exports.DEFAULT_ERROR_TEXT = 'validation error';