import { CommonTip, CommonRegexp } from './form.model'; export default class { // 数组必填项 static get 'required'() { return { required: true, message: '此为必填项' }; } // 数组必填项 static get 'required.array'() { return { type: 'array', required: true, message: '此为必填项' }; } // 最小长度 static minlength(params: any, tip: string) { if (params.number === undefined) return; return { validator: (rule: any, value: string, callback: any) => { value.length < parseInt(params.number) ? callback(new Error(tip)) : callback(); }, message: tip } } // 最大长度 static maxlength(params: any, tip: string) { if (params.number === undefined) return; return { validator: (rule: any, value: string, callback: any) => { value.length > parseInt(params.number) ? callback(new Error(tip)) : callback(); }, message: tip } } // 请输入1到100之间的正数 static get illegal() { return { validator: (rule: any, value: any, callback: any) => { return ((CommonRegexp.illegal).test(value)) ? callback(new Error(CommonTip.illegal)) : callback() }, message: CommonTip.illegal } } // 请输入1到100之间的正数 static get percentage() { return { validator: (rule: any, value: any, callback: any) => { (parseInt(value) < 0 || parseInt(value) > 100) ? callback(new Error('请输入1到100之间的正数')) : callback(); }, message: '请输入1到100之间的正数' } } /** * 字符串默认校验方法 * @param {string} type 检验类型 */ static validString(type: string) { if (!CommonRegexp[type]) return false; const tip = CommonTip[type]; return { validator: (rule: any, value: any, callback: any) => { return !((CommonRegexp[type]).test(value)) ? callback(new Error(tip)) : callback(); }, message: tip }; } /** * 对象默认校验方法,同时pattern类型特殊处理 * @author tanxj * @param {Object} options 校验参数 * @return any */ static validObject(options: any) { const { type, message, params, pattern, opposite } = options; let tip = message || CommonTip[type] || '格式错误'; params && Object.keys(params).forEach((key: string) => { tip = tip.replace(`{${key}}`, params[key]); }); // 自定义校验格式 if ((type !== 'pattern') && !CommonRegexp[type]) { if (!this[type]) return; return this[type](params, tip); } return { validator: (rule: any, value: any, callback: any) => { if (type === 'pattern' && !pattern) return callback(); const flag = ((type === 'pattern') ? pattern : CommonRegexp[type]).test(value); console.log(!opposite); return (opposite ? flag : !flag) ? callback(new Error(tip)) : callback(); }, message: tip }; } }