常用表单校验整理

export default (function () {
  return {
    /**
     * isFastClick判断是否为快速点击
     * 判断间隔的时间 默认500ms以内为快速点击
     * @param {num}
     * @return {bool} 是快速点击 true 不是 false
     */
    isFastClick: function (lastClickTime = 0, ms = 500) {
      var currTime = new Date().getTime(); // 当前时间的毫秒数
      if (currTime - lastClickTime < ms) {
        lastClickTime = currTime;
        return true;
      } else {
        lastClickTime = currTime;
        return false;
      }
    },
    // 校验银行卡号
    regBankCard: function (inp) {
      var reg = /^(\d{16,19})$/g;
      var cardNumber = inp.replace(/\s+/g, "");
      if (!reg.test(cardNumber)) {
        return false;
      } else {
        return true;
      }
    },
    /**
     * isDefine 校验传入值是否为空
     * @param {*} value
     * @return {bool} 校验结果
     */
    isDefine: function (value) {
      if (
        value == null ||
        value == "" ||
        value == "undefined" ||
        value == undefined ||
        value == "null" ||
        value == "(null)" ||
        value == "NULL" ||
        typeof value == "undefined"
      ) {
        return false;
      } else {
        value = value + "";
        value = value.replace(/\s/g, "");
        if (value == "") {
          return false;
        }
        return true;
      }
    },
    /**
     * getQueryString  从url中拿参数值param
     * @param {str} name 要拿的参数名  字符
     * @param {str} url  要从什么链接上面拿参数  字符  支持密文  可选填
     * @return {str} 参数值
     */
    getQueryString: function (name, url) {
      var searchUrl = window.location.search;
      if (url) {
        searchUrl = url.indexOf("?") ? url.substr(url.indexOf("?")) : searchUrl;
      }
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = searchUrl.substr(1).match(reg);
      if (r != null) {
        return decodeURIComponent(r[2]);
      }
      return "";
    },
    /**
     * 从页面url中获取json(url是未被编码的明文格式)
     * 
url格式:http://www.baidu.com?action=1&toobar=0
     * @param {str} url  页面的url,(url是未被编码的明文格式)
     * @returns {obj} json    json对象
     */
    getQueryJson: function (url) {
      var json = {};
      if (url) {
        var splits = url.split("?");
        if (splits && splits.length >= 2) {
          var array = splits[1].split("&");
          if (array && array.length > 0) {
            for (var i = 0; i < array.length; i++) {
              var params = array[i].split("="); // 拆分形式为key=value形式的参数
              json[params[0]] = params[1]; // 第一个参数表示key,第二个参数表示value
            }
          }
        }
      }
      return json;
    },
    /**
     * checkEmail 邮箱判断
     * @param {str} email 邮箱
     * @return {bool} 校验结果
     */
    checkEmail: function (email) {
      var patten = /^([a-zA-Z0-9]+[_|_|\-|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      if (!patten.test(email)) {
        return false;
      } else {
        return true;
      }
    },
    /**
     * checkIdcard 校验身份证
     * 包含 一代 和 二代  身份证校验
     * @param {str} idcard 身份证号
     * @return {bool} 校验结果
     */
    checkIdcard: function (num) {
      num = num.toUpperCase();
      //身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X。
      if (!/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num)) {
        return false;
      }
      //校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
      //下面分别分析出生日期和校验位
      var len, re;
      var arrSplit;
      var dtmBirth;
      var arrInt;
      var arrCh;
      var bGoodDay;
      var nTemp = 0;
      len = num.length;
      if (len == 15) {
        re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
        arrSplit = num.match(re);

        //检查生日日期是否正确
        dtmBirth = new Date(
          "19" + arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]
        );
        bGoodDay =
          dtmBirth.getYear() == Number(arrSplit[2]) &&
          dtmBirth.getMonth() + 1 == Number(arrSplit[3]) &&
          dtmBirth.getDate() == Number(arrSplit[4]);
        if (!bGoodDay) {
          // $toast("请输入有效的证件号码!",1500);
          return false;
        } else {
          //将15位身份证转成18位
          //校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
          arrInt = new Array(
            7,
            9,
            10,
            5,
            8,
            4,
            2,
            1,
            6,
            3,
            7,
            9,
            10,
            5,
            8,
            4,
            2
          );
          arrCh = new Array(
            "1",
            "0",
            "X",
            "9",
            "8",
            "7",
            "6",
            "5",
            "4",
            "3",
            "2"
          );
          num = num.substr(0, 6) + "19" + num.substr(6, num.length - 6);
          for (var i = 0; i < 17; i++) {
            nTemp += num.substr(i, 1) * arrInt[i];
          }
          num += arrCh[nTemp % 11];
          return true;
        }
      }
      if (len == 18) {
        re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
        arrSplit = num.match(re);

        //检查生日日期是否正确
        dtmBirth = new Date(
          arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]
        );
        bGoodDay =
          dtmBirth.getFullYear() == Number(arrSplit[2]) &&
          dtmBirth.getMonth() + 1 == Number(arrSplit[3]) &&
          dtmBirth.getDate() == Number(arrSplit[4]);
        if (!bGoodDay) {
          // $toast("请输入有效的证件号码!",1500);
          return false;
        } else {
          //检验18位身份证的校验码是否正确。
          //校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
          var valnum;
          arrInt = new Array(
            7,
            9,
            10,
            5,
            8,
            4,
            2,
            1,
            6,
            3,
            7,
            9,
            10,
            5,
            8,
            4,
            2
          );
          arrCh = new Array(
            "1",
            "0",
            "X",
            "9",
            "8",
            "7",
            "6",
            "5",
            "4",
            "3",
            "2"
          );
          for (var n = 0; n < 17; n++) {
            nTemp += num.substr(n, 1) * arrInt[n];
          }
          valnum = arrCh[nTemp % 11];
          if (valnum != num.substr(17, 1)) {
            // $toast("请输入有效的证件号码!",1500);
            return false;
          }
          return true;
        }
      }
      return false;
    },
    /**
     * 通过身份证号获取生日,性别
     * 返回:{birth:",sex:"}
     * getBirthByCid 通过身份证号获取生日,性别
     * @param {str}   身份证号码
     * @return {obj}  {birth: ", sex: "}
     */
    getInfoByIdcard: function (idcard) {
      var rel = {};
      var tmpStr = "";
      var sexStr = "";
      idcard = idcard.replace(/\s*/g, "");
      if (this.isDefine(idcard)) {
        if (idcard.length == 15) {
          tmpStr = idcard.substring(6, 12);
          var year = tmpStr.substring(0, 2);
          if (parseInt(year) < 20) {
            tmpStr = "20" + tmpStr;
          } else {
            tmpStr = "19" + tmpStr;
          }
          tmpStr =
            tmpStr.substring(0, 4) +
            "-" +
            tmpStr.substring(4, 6) +
            "-" +
            tmpStr.substring(6);
          sexStr = parseInt(idcard.substr(14, 1), 10) % 2 ? "男" : "女";
        } else {
          tmpStr = idcard.substring(6, 14);
          tmpStr =
            tmpStr.substring(0, 4) +
            "-" +
            tmpStr.substring(4, 6) +
            "-" +
            tmpStr.substring(6);
          sexStr = parseInt(idcard.substr(16, 1), 10) % 2 ? "男" : "女";
        }
      } else {
        tmpStr = "";
        sexStr = "";
      }
      rel.birth = tmpStr;
      rel.sex = sexStr;
      return rel;
    },
    /**
     * getSexByIdcard  根据身份证号判断性别
     * @param {str}  idcard  身份证号
     * @return {str} "男"/"女"
     */
    getSexByIdcard: function (idcard) {
      if (parseInt(idcard.substr(16, 1)) % 2 == 1) {
        return "男";
      } else {
        return "女";
      }
    },
    /**
     * trimAll 字符串去空格
     * @param {string} str
     * @return {string} 去空格之后的字符串
     */
    trimAll: function (str) {
      if (!str) {
        return "";
      }
      return str.replace(/\s+/g, "");
    },
    /* 计算字符串长度(英文占1个字符,中文汉字占2个字符) */
    getStrLen: function (str) {
      var strlength = str.length;
      for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) {
          // 判断输入的是否是汉字,如果是汉字的话,则字符串长度加2
          strlength += 1;
        }
      }
      return strlength;
    },
    /**
     * 通过身份证号获取年龄
     * @param {str} idNumber:身份证号
     * @return {str} age 年龄
     */
    getAgeByIdcard: function (idNumber) {
      var age = "";
      var tmpStr = "";
      idNumber = this.trimAll(idNumber);
      if (idNumber.length == 15) {
        tmpStr = idNumber.substring(6, 12);
        var year = tmpStr.substring(0, 2);
        if (parseInt(year) < 20) {
          tmpStr = "20" + tmpStr;
        } else {
          tmpStr = "19" + tmpStr;
        }
        tmpStr =
          tmpStr.substring(0, 4) +
          "-" +
          tmpStr.substring(4, 6) +
          "-" +
          tmpStr.substring(6);
      } else {
        tmpStr = idNumber.substring(6, 14);
        tmpStr =
          tmpStr.substring(0, 4) +
          "-" +
          tmpStr.substring(4, 6) +
          "-" +
          tmpStr.substring(6);
      }
      age = this.getAgeByBirth(tmpStr);
      return age;
    },
    /**
     * getAge 根据出生日期获取年龄
     * @param {str} birthday 出生日期
     * @return {num} 年龄
     */
    getAgeByBirth: function (birthday) {
      var r = birthday.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
      if (r == null) {
        return false;
      }
      var birth = new Date(r[1], r[3] - 1, r[4]);
      if (
        birth.getFullYear() == r[1] &&
        birth.getMonth() + 1 == r[3] &&
        birth.getDate() == r[4]
      ) {
        var today = new Date();
        today.setDate(today.getDate() + 1);
        var age = today.getFullYear() - r[1];
        if (today.getMonth() > birth.getMonth()) {
          return age;
        }
        if (today.getMonth() == birth.getMonth()) {
          if (today.getDate() >= birth.getDate()) {
            return age;
          } else {
            return age - 1;
          }
        }
        if (today.getMonth() < birth.getMonth()) {
          return age - 1;
        }
      }
      return age;
    },
    /**
     * 校验手机号码
     * 非1开头的号码;
     * 重复数字超过7位(含7位)
     * 数字递增或递减超过7位(含7位);
     * 两位数字组成的组合重复出现超4次 如13838383838
     * 13800138000
     * 含有非数字字符(如*#¥);
     * @param {str} 手机号码
     * @return {obj} 校验结果 {result: bool, title: "} 当result是true时, 没有title
     */
    checkPhone: function (phone) {
      if (phone == "") {
        return {
          result: false,
          title: "手机号不能为空"
        };
      }
      var reg = /^1[3,4,5,6,7,8,9]\d{9}$/;
      if (!reg.test(phone)) {
        return {
          result: false,
          title: "请正确输入手机号"
        };
      }
      var sub = phone.substr(2);
      var sub2 = phone.substr(3);
      var len = sub.length;
      var offset = 0;
      var num = 0;
      for (var i = len - 1; i > 0; i--) {
        var a = parseInt(sub[i]);
        var b = parseInt(sub[i - 1]);
        if (a - b == 1 || b - a == 1) {
          num++;
          if (num >= 6) {
            return {
              result: false,
              title: "请正确输入手机号"
            };
          }
        } else {
          num = 0;
        }
        if (a - b == 0) {
          offset++;
          if (offset >= 6) {
            return {
              result: false,
              title: "请正确输入手机号"
            };
          }
        } else {
          offset = 0;
        }
      }
      if (phone == "13800138000") {
        return {
          result: false,
          title: "请正确输入手机号"
        };
      }
      if (
        sub2[0] + sub2[1] == sub2[2] + sub2[3] &&
        sub2[4] + sub2[5] == sub2[6] + sub2[7] &&
        sub2[4] + sub2[5] == sub2[0] + sub2[1]
      ) {
        return {
          result: false,
          title: "请正确输入手机号"
        };
      }
      return {
        result: true
      };
    },
    /* 手机号 脱敏 补星 185 **** 4008 */
    desensitizePhone: function (obj) {
      if (obj != undefined) {
        return obj.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
      }
    },
    /**
       * coreInfo 获取浏览器内核信息
       * @return {obj} 
       * {
          trident: ",    //IE内核                
          presto: ",     //opera内核                
          webKit: ",     //苹果、谷歌内核                
          gecko: ",      //火狐内核                
          mobile: ",     //是否为移动终端                
          ios: ",        //ios终端                
          android: ",    //android终端或者uc浏览器                
          iPhone: ",     //是否为iPhone或者QQHD浏览器                
          iPad: ",       //是否iPad                
          webApp: "      //是否web应该程序,没有头部与底部            
        }
       */
    coreInfo: function () {
      var u = navigator.userAgent;
      return {
        trident: u.indexOf("Trident") > -1,
        presto: u.indexOf("Presto") > -1,
        webKit: u.indexOf("AppleWebKit") > -1,
        gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1,
        mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/),
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
        android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1,
        iPhone: u.indexOf("iPhone") > -1 || u.indexOf("Mac") > -1,
        iPad: u.indexOf("iPad") > -1,
        webApp: u.indexOf("Safari") == -1
      };
    },
    /*判断是否是微信内置浏览器*/
    isWeixin: function () {
      // 对浏览器的UserAgent进行正则匹配,不含有微信独有标识的则为其他浏览器
      var useragent = navigator.userAgent.toLowerCase();
      if (useragent.match(/MicroMessenger/i) == "microMessenger") {
        return true;
      } else {
        return false;
      }
    },
    /* 判断是否在app中 */
    isApp: function () {
      return (
        window.hasOwnProperty("android") ||
        (window.hasOwnProperty("webkit") &&
          window.webkit.messageHandlers.hasOwnProperty("iphone"))
      );
    },
    /**
     * 判断当前页面是否在android平台内
     * @return {bool}  如果是,返回true;否则返回false
     */
    isAndroid: function () {
      return window.hasOwnProperty("android");
    },
    /**
     * 判断当前页面是否在iOS平台内
     * @return {bool}  如果是,返回true;否则返回false
     */
    isiOS: function () {
      return (
        window.hasOwnProperty("webkit") &&
        window.webkit.messageHandlers.hasOwnProperty("iphone")
      );
    },
    /* 判断是否为数组 */
    isArray: function (obj) {
      return Object.prototype.toString.call(obj) === "[object Array]";
    },
    /**
     * isFunc 校验传入值是否为function
     * @param {*} value
     * @return {Boolean} 校验结果
     */
    // isFunc: function (f) {
    // 	if (typeof (f) === "function" && (f instanceof Function)) {
    // 		return true
    // 	} else {
    // 		return false
    // 	}
    // },
    isFunc: function () {
      return (
        Object.prototype.toString.call(function () {
          return 1;
        }) === "[object Function]"
      );
    },
    /* 小于10的数之前补零 */
    toTwo: function (n) {
      return n < 10 ? "0" + n : "" + n;
    },
    /* formatDateForRule 格式化时间
      * @param {date为具体的日期,rule为不同的日期格式}  
        如:(new Date(),"yyyy/MMdd")=>"2018/04/23",
        (new Date(),"yyyy-MM-dd")=>"2018-04-23"
        (new Date(),"yyyy-MM-dd hh:mm:ss")=>"2018-04-23 08:09:04"
        (new Date(),"yyyy-MM-dd hh:mm:ss.S")=>"2018-04-23 08:09:06.423"
        (new Date(),"yyyy-MM-dd E hh:mm:ss")=>"2018-04-23 二 20:09:04"
        (new Date(),"yyyy-MM-dd EE hh:mm:ss")=>"2018-04-23 周二 20:09:04"
        (new Date(),"yyyy-MM-dd EEE hh:mm:ss")=>"2018-04-23 星期二 20:09:04"
      * @return {按照不同的rule格式化后的日期}
      */
    formatDateForRule: function (date, rule) {
      var show_day = new Array("一", "二", "三", "四", "五", "六", "日");
      var t = new Date(date);
      var y = t.getFullYear();
      var M = t.getMonth() + 1;
      var d = t.getDate();
      var w = t.getDay();
      var h = t.getHours();
      var m = t.getMinutes();
      var s = t.getSeconds();
      var ss = t.getMilliseconds();
      M = this.toTwo(M);
      d = this.toTwo(d);
      h = this.toTwo(h);
      m = this.toTwo(m);
      s = this.toTwo(s);
      var now_time;
      switch (rule) {
        case "yyyy/MMdd":
          now_time = y + "/" + M + "/" + d;
          break;
        case "yyyy-MM-dd":
          now_time = y + "-" + M + "-" + d;
          break;
        case "yyyy-MM-dd hh:mm:ss":
          now_time = y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s;
          break;
        case "yyyy-MM-dd hh:mm:ss.S":
          now_time =
            y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s + "." + ss;
          break;
        case "yyyy-MM-dd E hh:mm:ss":
          now_time =
            y +
            "-" +
            M +
            "-" +
            d +
            show_day[w - 1] +
            h +
            ":" +
            m +
            ":" +
            s +
            "." +
            ss;
          break;
        case "yyyy-MM-dd EE hh:mm:ss":
          now_time =
            y +
            "-" +
            M +
            "-" +
            d +
            " 周" +
            show_day[w - 1] +
            " " +
            h +
            ":" +
            m +
            ":" +
            s;
          break;
        case "yyyy-MM-dd EEE hh:mm:ss":
          now_time =
            y +
            "年" +
            M +
            "月" +
            d +
            "日" +
            " 星期" +
            show_day[w - 1] +
            " " +
            h +
            ":" +
            m +
            ":" +
            s;
          break;
      }
      return now_time;
    },
    /**
     * formatDate 时间戳转年月日
     * @param {num|str} ns 时间戳
     * @param {str} [symbol="-"] symbol 默认为"-""
     * @example formatDate(new Date())  返回 2018-07-24
     */
    formatDate: function (nS, symbol) {
      symbol = symbol ? symbol : "-";
      var DD = new Date(Number(nS));
      var year = this.toTwo(DD.getFullYear());
      var month = this.toTwo(DD.getMonth() + 1);
      var day = this.toTwo(DD.getDate());
      var time = year + symbol + month + symbol + day;
      return time;
    },
    /**
     * 格式化时间字符窜,将毫秒数转化成时间格式
     * @param {str} _longtime    毫秒数,字符串
     * @return {str}     时间格式:hh:mm:ss  19:09:56
     */
    formatTime: function (_longtime) {
      if (_longtime) {
        var longtime = Number(_longtime);
        var date = new Date(longtime);
        var _hour = date.getHours(); // 时
        var _minute = date.getMinutes(); // 分
        var _second = date.getSeconds(); // 秒
        if (_hour < 10) {
          _hour = "0" + _hour;
        }
        if (_minute < 10) {
          _minute = "0" + _minute;
        }
        if (_second < 10) {
          _second = "0" + _second;
        }
        return _hour + ":" + _minute + ":" + _second;
      }
    },
    /* 存localStorage */
    setLocVal: function (key, value) {
      try {
        window.localStorage[key] = value;
      } catch (err) {
        // console.log(err);
      }
    },
    /* 取localStorage, 失败的话走cb */
    getLocVal: function (key, cb) {
      try {
        window.localStorage["1"] = 1;
        var value = window.localStorage[key];
        return value;
      } catch (e) {
        cb && cb();
      }
    },
    /* 清local, 报错的话执行cb */
    clearLocVal: function (key, cb) {
      try {
        if (key) window.localStorage.removeItem(key);
        else window.localStorage.clear();
      } catch (e) {
        cb && cb();
      }
    },
    /* 车牌号校验 */
    carNoCheck: function (carMarknumber) {
      var carMarkreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[A-Z]{1}[A-Z0-9]{4,5}[A-Z0-9挂学警港澳]{1}$/;
      if (carMarkreg.test(carMarknumber)) {
        return true;
      } else {
        return false;
      }
    },
    /* 车架号校验 */
    frameNoCheck: function (frameNo) {
      var frameNoReg = /^([a-hj-npr-z]|[A-HJ-NPR-Z]|[0-9]){17}$/;
      var strVin = /^[A-Za-z]+$/; //车架号不能为纯字母
      var strNumVin = /^[0-9]+$/; //车架号不能为纯数字
      if (frameNoReg.test(frameNo)) {
        frameNo = frameNo.toUpperCase();
      } else {
        return false;
      }
      if (strVin.test(frameNo)) {
        //车架号不能为纯字母
        return false;
      }
      if (strNumVin.test(frameNo)) {
        //车架号不能为纯数字
        return false;
      }
      return true;
    },
    /**
     * 发动机号校验
     */
    engineNoCheck: function (engineNo) {
      var re = /^(?!-)(?!.*?-$)[A-Z0-9-]{4,30}$/;
      if (re.test(engineNo)) {
        return true;
      } else {
        return false;
      }
    },
    /**
     * modifyStr,自动替换字符串中的连续的特殊字符,只保留连续字符中的第一个特殊字符
     * @param {str} name 原值
     * @return {str}     新值
     * @example  modifyStr(马,,._安徽$~哈!)  结果: 马,安徽$哈!
     */
    modifyStr: function (name) {
      var newName = this.trimAll(name);
      var name1 = "";
      var test1 = /[\u4e00-\u9fa5]/;
      var test2 = /[a-zA-Z]/;
      var isFirst = true;
      for (var i = 0; i < newName.length; i++) {
        var c = newName.charAt(i);
        if (test1.test(c) || test2.test(c) || /\s/.test(c)) {
          name1 += c;
          isFirst = true;
        } else {
          if (isFirst) {
            name1 += c;
            isFirst = false;
          }
        }
      }
      newName = name1;

      var name3 = "";
      isFirst = true;
      for (var n = 0; n < newName.length; n++) {
        var d = newName.charAt(n);
        if (/\s/.test(d)) {
          if (isFirst) {
            name3 += d;
            isFirst = false;
          }
        } else {
          name3 += d;
          isFirst = true;
        }
      }
      newName = name3;

      var name2 = "";
      for (var m = 0; m < newName.length; m++) {
        var q = newName.charAt(m);
        if (/\s/.test(q)) {
          var p = newName.charAt(m - 1);
          var r = newName.charAt(m + 1);
          if (test2.test(p) && test2.test(r)) {
            name2 += q;
          }
        } else {
          name2 += q;
        }
      }
      return name2;
    },
    /**
     * checkusername 校验  财险  姓名格式是否正确
     * @param {str} name  需要校验的姓名值
     * @return {obj}     校验结果
     * 校验通过 返回: {result: 转化或原本正确的姓名},  校验失败  返回: {result: false, title: 错误信息}
     */
    checkusername: function (name) {
      var strlength = this.getStrLen(
        name.replace(/^\s+|\s+$/g, "").replace(/\s+/g, " ")
      );
      // var errMsg = "姓名长度需为3至50个字符(字母、数字、符号是相当于1个字符,1个汉字相当于两个字符),且不得出现数字或特殊符号。";
      if (strlength <= 0) {
        return {
          result: false,
          title: "姓名不能为空"
        };
      }
      if (strlength < 3 || strlength > 50) {
        return {
          result: false,
          title: "姓名长度不符"
        };
      }
      if (/[0-9]/.test(name)) {
        return {
          result: false,
          title: "姓名中不得出现数字或特殊字符!"
        };
      }
      var newName = this.modifyStr(name);
      //不允许出现下面的字符
      var test2 = new RegExp(
        "[`~!@#*$^&()=|{}':;'*€£\\[\\]<>/?~!@#¥……&()|{}【】‘;:”“'?]"
      );
      var test3 = /\d+/g;
      if (test2.test(newName) || test3.test(newName)) {
        return {
          result: false,
          title: "姓名中不得出现数字或特殊字符!"
        };
      }
      // 不允许既有汉字又有字母
      if (/[\u4e00-\u9fa5]/.test(newName) && /[a-zA-Z]/.test(newName)) {
        return {
          result: false,
          title: "姓名格式不正确"
        };
      }
      //•_-不能出现在第一个或者最后一个
      if (/^•|^_|^-|^·|·$|•$|_$|-$/.test(newName)) {
        return {
          result: false,
          title: "姓名格式不正确"
        };
      }

      newName = newName.replace(/·+/g, "·");
      newName = newName.replace(/_+/g, "_");
      newName = newName.replace(/-+/g, "-");
      newName = newName.replace(/\s+/g, "");

      var test6 = /\.|\.|。|.|,|,|、|•/.test(newName);
      if (test6) {
        if (confirm("您输入的姓名中含有非法字符, 已将其转换为'·', 请确认")) {
          newName = newName.replace(/\.+|\.+|。+|.+|,+|,+|、+|•+/g, "·");
          return {
            result: newName
          };
        } else {
          // 用户不同意
          return {
            result: false,
            title: "姓名中不得出现数字或特殊字符!"
          };
        }
      } else {
        // 符合
        return {
          result: newName
        };
      }
    },
    /**
     * utf16转utf8
     * @param {Object} str
     */
    utf16to8: function (str) {
      var out, i, len, c;
      out = "";
      len = str.length;
      for (i = 0; i < len; i++) {
        c = str.charCodeAt(i);
        if (c >= 0x0001 && c <= 0x007f) {
          out += str.charAt(i);
        } else if (c > 0x07ff) {
          out += String.fromCharCode(0xe0 | ((c >> 12) & 0x0f));
          out += String.fromCharCode(0x80 | ((c >> 6) & 0x3f));
          out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
        } else {
          out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1f));
          out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f));
        }
      }
      return out;
    },
    /**
     * utf8转utf16
     * @param {Object} str
     */
    utf8to16: function (str) {
      var out, i, len, c;
      var char2, char3;
      out = "";
      len = str.length;
      i = 0;
      while (i < len) {
        c = str.charCodeAt(i++);
        switch (c >> 4) {
          case 0:
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            // 0xxxxxxx
            out += str.charAt(i - 1);
            break;
          case 12:
          case 13:
            // 110x xxxx 10xx xxxx
            char2 = str.charCodeAt(i++);
            out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
            break;
          case 14:
            // 1110 xxxx10xx xxxx10xx xxxx
            char2 = str.charCodeAt(i++);
            char3 = str.charCodeAt(i++);
            out += String.fromCharCode(
              ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
            );
            break;
        }
      }
      return out;
    }
  };
})();

你可能感兴趣的:(常用工具类)