UNPKG

@jypj/validate-control

Version:

一个简单校验器,用于验证传入的数据是否符合要求

143 lines (122 loc) 3.56 kB
// import {getDataType} from "./utils"; function getDataType(data){ return Object.prototype.toString.call(data).slice(8, -1) } class ValidateRules { /** @type {null} 需要校验的数据*/ input = null /** @type {null} 错误提示信息*/ error_msg = null /*** @type {null} true 通过 false 未通过*/ pass = true constructor(input, error_msg) { this.input = input this.error_msg = error_msg } /** * 重新设置需要校验的数据 * @param input - 需要校验的数据 */ value(input = null) { if (!this.pass) return this this.input = input return this } /** * 是否为手机号码 * @return {boolean} */ isMobile() { const reg = /^(13[0-9]{1}|14[5|7|9]{1}|15[0-3|5-9]{1}|166|17[0-3|5-8]{1}|18[0-9]{1}|19[0-9]{1}){1}\d{8}$/ return reg.test(this.input) } /** * 是否为空 * @return {boolean} */ isRequired() { // 先判断空数组或者空对象 let data = this.input getDataType(data) === 'Object' && (data = Object.keys(data)) return getDataType(data) === 'Array' ? data.length === 0 : !!data } /** * 是否为身份证 * @return {boolean} */ isIdCard() { const cP = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/ return cP.test(this.input) } /** * 自定义正则校验 * @param reg - 正则 * @return {boolean} */ isRegExp(reg) { return new RegExp(reg).test(this.input) } /** * 判断是否为最多两位小数点的金额 * @return {boolean} */ isMoneyFloat () { return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(this.input) } /** * 是否为外链(携带http / https) * @return {boolean} */ isExternal () { return /^(https?:|mailto:|tel:)/.test(this.input) } /** * 是否为邮箱 * @return {boolean} */ isEmail(){ return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(this.input) } /** * 是否全为中文 * @return {boolean} */ isChinese(){ return /^[\u4e00-\u9fa5]{0,}$/.test(this.input) } /** * 判断字符串中是否包含着指定的字符串 * @param text * @return {boolean} */ isExistText(text){ const _input = String(this.input) if (!_input) return false return _input.includes(text) } } /** * 校验器,使用时需要 new * @property ValidateControl.validate 校验函数 * @class */ class ValidateControl extends ValidateRules { constructor(input = null, error_msg = null) { super(input, error_msg) } /** * 校验函数,传入rule 以及 错误提示信息即可 * @param {string} rule - 校验规则,内部已集成一些校验可以调用 * @param {string} error_msg - 错误提示信息 * @param {any} props - 传输给指定规则的参数,有些规则函数需要额外的传输数据 * @return {ValidateControl} 返回实例 */ validate(rule = null, error_msg = null,props = null) { if (!this.pass) return this if (!rule || !error_msg) return console.error('rule and error_msg is required') this.pass = this[rule](props) this.error_msg = error_msg return this } } export default ValidateControl