util.js 2.3 KB

module.exports = {
    sleep: (time) => {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve();
            }, time);
        });
    },
    get: (object, path, defaultValue) => {
        return (!Array.isArray(path) ? path.replace(/\[/g, '.').replace(/\]/g, '').split('.') : path)
            .reduce((o, k) => (o || {})[k], object) || defaultValue;
    },
    getPathInfo: () => {
        const pages = getCurrentPages();
        const len = pages.length;
        const curPath = pages[len - 1] && pages[len - 1].route;
        const prePath = pages[len - 2] && pages[len - 2].route;

        return {curPath, prePath};
    },
    dateFormat: (times, format) => {
        format = format || 'YYYY/MM/DD HH:mm:ss';

        let dateObj = times ? new Date(times.replace(/-/g, '/')) : new Date();
        let year = dateObj.getFullYear();
        let month = dateObj.getMonth() + 1;
        let day = dateObj.getDate();

        let hour = dateObj.getHours();
        let minute = dateObj.getMinutes();
        let second = dateObj.getSeconds();

        [year, month, day, hour, minute, second] = [year, month, day, hour, minute, second].map(n => {
            n = n.toString();
            return n[1] ? n : '0' + n;
        });

        return format.replace('YYYY', year).replace('MM', month).replace('DD', day)
            .replace('HH', hour).replace('mm', minute).replace('ss', second);
    },
    validateMobile: (area, mobile) => {
        // 手机号码验证规则
        let phoneRegx = {
            '+86': /^1[0-9]{10}$/,
            '+852': /^[965]{1}[0-9]{7}$/,
            '+853': /^[0-9]{8}$/,
            '+886': /^[0-9]{10}$/,
            '+65': /^[98]{1}[0-9]{7}$/,
            '+60': /^1[1234679]{1}[0-9]{8}$/,
            '+1': /^[0-9]{10}$/,
            '+82': /^01[0-9]{9}$/,
            '+44': /^7[789][0-9]{8}$/,
            '+81': /^0[9|8|7][0-9]{9}$/,
            '+61': /^[0-9]{11}$/
        };

        return phoneRegx[`+${area}`].test(mobile);
    },
    validateIdCard: (idCard) => {
        // 身份证验证规则-身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X
        let idCardRegx = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;

        return idCardRegx.test(idCard);
    }
};