常见验证

Posted jscai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常见验证相关的知识,希望对你有一定的参考价值。

export default {
    // 两个对象合并
    extend: function(target, source, deep) {
        target = target || {};
        var sType = typeof source,
            i = 1,
            options;
        if (sType === ‘undefined‘ || sType === ‘boolean‘) {
            deep = sType === ‘boolean‘ ? source : false;
            source = target;
            target = this;
        }
        if (
            typeof source !== ‘object‘ &&
            Object.prototype.toString.call(source) !== ‘[object Function]‘
        ) {
            source = {};
        } else i = 2;
        while (i <= 2) {
            options = i === 1 ? target : source;
            if (options != null) {
                for (var name in options) {
                    var src = target[name],
                        copy = options[name];
                    if (target === copy) {
                        continue;
                    }
                    if (deep && copy && typeof copy === ‘object‘ && !copy.nodeType) {
                        target[name] = this.extend(
                            src || (copy.length != null ? [] : {}),
                            copy,
                            deep
                        );
                    } else if (copy !== undefined) {
                        target[name] = copy;
                    }
                }
            }
            i++;
        }
        return target;
    },

    /**
     * 格式化日期
     *
     * @author  Siah
     *
     * @param   date
     * @param   format
     * @return  格式化过的日期 如 2020-01-01
     */
    formatDate(date, format) {
        // 控制时区
        if (!date) {
            return ‘空‘;
        }
        if (date.indexOf(‘.‘) > -1) {
            date = date.substr(0, date.indexOf(‘.‘));
        }
        var tempDate = new Date(date + ‘+0800‘);
        if (tempDate === ‘Invalid Date‘) {
            date = date.replace(/T/g, ‘ ‘);
            date = date.replace(/-/g, ‘/‘);
            tempDate = new Date(date + ‘+0800‘);
        }
        tempDate.toLocaleDateString();

        if (!format) format = ‘yyyyMMddHHmmss‘;
        // 格式化时间
        var year = tempDate.getFullYear();
        var months =
            (tempDate.getMonth() > 8 ? ‘‘ : ‘0‘) + (tempDate.getMonth() + 1);
        var days = (tempDate.getDate() > 9 ? ‘‘ : ‘0‘) + tempDate.getDate();
        var hours = (tempDate.getHours() > 9 ? ‘‘ : ‘0‘) + tempDate.getHours();
        var minutes =
            (tempDate.getMinutes() > 9 ? ‘‘ : ‘0‘) + tempDate.getMinutes();
        var secounds =
            (tempDate.getSeconds() > 9 ? ‘‘ : ‘0‘) + tempDate.getSeconds();

        format = format.replace(/yyyy/, year);
        format = format.replace(/MM/, months);
        format = format.replace(/dd/, days);
        format = format.replace(/HH/, hours);
        format = format.replace(/mm/, minutes);
        format = format.replace(/ss/, secounds);
        return format;
    },

    // 返回一个全地址
    resolveUrl(url) {
        var a = document.createElement(‘a‘);
        a.href = url;
        return a.href;
    },

    //* ************************************************
    //*                                               *
    //*                     cookie                    *
    //*                                               *
    //* ************************************************
    addcookie(name, value, expireHours) {
        var cookieString = name + ‘=‘ + escape(value);
        // 判断是否设置过期时间
        expireHours = expireHours || 10000;

        var date = new Date();
        date.setTime(date.getTime() + expireHours * 3600 * 1000);
        cookieString =
            cookieString + ‘; expires=‘ + date.toGMTString() + ‘; path=/‘;

        document.cookie = cookieString;
    },

    getcookie(name) {
        var strcookie = document.cookie;
        var arrcookie = strcookie.split(‘; ‘);
        for (var i = 0; i < arrcookie.length; i++) {
            var arr = arrcookie[i].split(‘=‘);
            if (arr[0] == name) return arr[1];
        }
        return ‘‘;
    },

    /**
     * 验证用户浏览器是否是微信浏览器
     * @author  Siah
     *
     * @return  是微信浏览器返回true否则返回false
     */
    isWeiXinFun() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == ‘micromessenger‘) {
            return true;
        } else {
            return false;
        }
    },

    /**
     * 验证用户浏览器是否是微博内置浏览器
     * @author  Siah
     *
     * @return  是微博内置浏览器返回true否则返回false
     */
    isWeibo() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/weibo/i) == ‘weibo‘) {
            return true;
        } else {
            return false;
        }
    },

    isZhifubao() {
        var ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/ali/i) == ‘ali‘) {
            return true;
        } else {
            return false;
        }
    },

    //* ************************************************
    //*                                               *
    //*                     query string              *
    //*                                               *
    //* ************************************************

    getQueryStringByName(name) {
        var result = this.location.search.match(
            new RegExp(‘[?&]‘ + name + ‘=([^&]+)‘, ‘i‘)
        );
        if (result == null || result.length < 1) {
            return ‘‘;
        }
        return decodeURIComponent(result[1]);
    },

    /**
     * 验证用户设备来源
     * @author  Siah
     *
     * @return  object
     */
    userAgent() {
        var sUserAgent = navigator.userAgent.toLowerCase();

        var o = {};
        o.isIpad = /ipad/i.test(sUserAgent);
        o.isIphone = /iphone os/i.test(sUserAgent);
        o.isUc7 = /rv:1.2.3.4/i.test(sUserAgent);
        o.isUc = /ucweb/i.test(sUserAgent);
        o.isandroid = /android/i.test(sUserAgent);
        o.isWM = /windows mobile/i.test(sUserAgent);

        o.isPhone = o.isIphone || o.isAndroid || o.isWM || o.isUc7 || o.isUc;
        o.isMobile = o.isIpad || o.isPhone || o.isAndroid;
        o.isPc = !o.isMobile;
        o.isios = o.isIpad || o.isIphone;

        return o;
    },

    /**
     * JS验证邮件地址是否合法
     * @author  Siah
     *
     * @param   email
     * @return  合法返回true;不合法返回false
     */
    checkEmail(email) {
        var re = /^w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$/;
        return re.test(email);
    },

    /**
     * JS获取字符串长度(区分中英文) 中文算2个字,英文一个
     * @author  Siah
     *
     * @param   string  电话号码
     * @return 返回字符串长度
     */
    getStrLength(str) {
        var cArr = str.match(/[^x00-xff]/gi);
        return str.length + (cArr == null ? 0 : cArr.length);
    },

    /**
     * JS获取字符串长度(区分中英文) 中文算2个字,英文一个
     * @author  Siah
     *
     * @param   string  电话号码
     * @return 返回字符串长度
     */
    setGlobal() {
        var logoImg = document.querySelector(‘.wap-logo img‘),
            bannerImg = document.querySelector(‘.wap-static-banner img‘);
        activityConfig = window.store.activityConfig;
        activityConfig.logo.imgH = logoImg.offsetHeight;
        activityConfig.logo.imgW = logoImg.offsetWidth;
        activityConfig.banner.imgH = bannerImg.offsetHeight;
        activityConfig.banner.imgW = bannerImg.offsetWidth;
    },
    getRem(px) {
        return ~~px.substring(0, px.length - 2) / 12 + ‘rem‘; // rem
    },
    /**
     * 检查手机号码是否合法
     * @author  Siah
     *
     * @param   string  手机号码
     * @return 合法返回true;不合法返回flase
     */
    checkMobile(string) {
        return /^1[3-9]+d{9}$/.test(string);
    },

    /**
     * 验身份证号码是否正确
     * @author  Siah
     *
     * @param   num     身份证号码
     * @return 合法返回true;不合法返回flase
     */
    isIdCardNo(num) {
        var factorArr = new Array(
            7,
            9,
            10,
            5,
            8,
            4,
            2,
            1,
            6,
            3,
            7,
            9,
            10,
            5,
            8,
            4,
            2,
            1
        );
        var error;
        var varArray = new Array();
        var intValue;
        var lngProduct = 0;
        var intCheckDigit;
        var intStrLen = num.length;
        var idNumber = num;
        // initialize
        if (intStrLen != 15 && intStrLen != 18) {
            // error = "输入身份证号码长度不对!";
            // alert(error);
            // frmAddUser.txtIDCard.focus();
            return false;
        }
        // check and set value
        for (i = 0; i < intStrLen; i++) {
            varArray[i] = idNumber.charAt(i);
            if ((varArray[i] < ‘0‘ || varArray[i] > ‘9‘) && i != 17) {
                // error = "错误的身份证号码!.";
                // alert(error);
                // frmAddUser.txtIDCard.focus();
                return false;
            } else if (i < 17) {
                varArray[i] = varArray[i] * factorArr[i];
            }
        }
        if (intStrLen == 18) {
            // check date
            var date8 = idNumber.substring(6, 14);
            if (IsDate(date8) == false) {
                // error = "身份证中日期信息不正确!.";
                // alert(error);
                return false;
            }
            // calculate the sum of the products
            for (i = 0; i < 17; i++) {
                lngProduct = lngProduct + varArray[i];
            }
            // calculate the check digit
            intCheckDigit = 12 - (lngProduct % 11);
            switch (intCheckDigit) {
                case 10:
                    intCheckDigit = ‘X‘;
                    break;
                case 11:
                    intCheckDigit = 0;
                    break;
                case 12:
                    intCheckDigit = 1;
                    break;
            }
            // check last digit
            if (varArray[17].toUpperCase() != intCheckDigit) {
                // error = "身份证效验位错误!正确为: " + intCheckDigit + ".";
                // alert(error);
                return false;
            }
        } else {
            // length is 15
            // check date
            var date6 = ‘19‘ + idNumber.substring(6, 12);
            if (IsDate(date6) == false) {
                // alert("身份证日期信息有误!.");
                return false;
            }
        }
        // alert ("Correct.");
        return true;
    },

    /**
     * 随机数组
     * @author  Siah
     *
     * @param   array     原数组
     * @return 随机打乱过的数组
     */
    shuffleArray(array) {
        var currentIndex = array.length,
            temporaryValue,
            randomIndex;

        while (currentIndex !== 0) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    },
    getParms(checkToken, item) {
        var f = false,
            Data = ‘‘;
        if (checkToken) {
            Data +=
                localStorage.getItem(‘userId‘) +
                ‘|$@^‘ +
                localStorage.getItem(‘token‘) +
                ‘|$@^‘;
            f = true;
        }
        if (item != null) {
            for (var i = 0; i < item.length; i++) {
                Data += item[i] + ‘|$@^‘;
                f = true;
            }
        }
        if (f) Data = Data.substring(0, Data.length - 4);
        if (checkToken)
            Data =
                localStorage.getItem(‘guid‘) +
                ‘-‘ +
                base64.encode64(base64.utf16to8(Data));
        else Data = this.Guid(3, 32) + base64.encode64(base64.utf16to8(Data));
        return Data;
    },
    Guid(len, radix) {
        var chars = ‘0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz‘.split(
            ‘‘
        );
        var uuid = [],
            i;
        radix = radix || chars.length;
        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = ‘-‘;
            uuid[14] = ‘4‘;

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | (Math.random() * 16);
                    uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join(‘‘);
    },
    getArgsFromUrl(sArgName) {
        var sHref = window.location.search; //因为有#所以用search取出来是"",改用hash
        //var sHref = window.location.hash;
        var args = sHref.split(‘?‘);
        var retval = ‘‘;
        if (args[0] == sHref) {
            return retval;
        }
        var str = args[1];
        args = str.split(‘&‘);
        for (var i = 0; i < args.length; i++) {
            str = args[i];
            var arg = str.split(‘=‘);
            if (arg.length <= 1) continue;
            if (arg[0] == sArgName) retval = arg[1];
        }
        return retval;
    },
    getItem(item, n1, n2) {
        try {
            var res = item[n1][n2];
            return res;
        } catch (e) {
            return ‘(空)‘;
        }
    }
};

 

以上是关于常见验证的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 快速代码片段,用于在统计(阻止)/ dev / rdsk中的设备时验证fstat64和stat64的行为。

Android 实用代码片段

Android 实用代码片段

覆盖一个常见的片段帮助其他标签片段

爬虫遇到头疼的验证码?Python实战讲解弹窗处理和验证码识别

教程4 - 验证和权限