IP批量格式化处理vue
标签搜索
侧边栏壁纸
博主昵称
2c

  • 累计撰写 19 篇文章
  • 累计收到 12 条评论

IP批量格式化处理vue

2c
2c
2023-01-09 / 0 评论 / 9 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年01月09日,已超过466天没有更新,若内容或图片失效,请留言反馈。

最近遇到个IP批量格式化的功能,废话不说 开始上代码

首先输入框输入 大量IP 用户会输入各种恶心变态的 中文的 逗号 句号 反正就是各种符号我们要先处理一下

formIp() {
      // console.log(this.formData.ip);
      // 非数字和点的字符变成逗号
      let str = this.formData.ip.replace(/[^\d.\-\/]/gi, ",");
      // console.log(str);
      // 把ip截取成数组
      let ipArr = str.split(",");
      // console.log(ipArr);
      this.ipArr = ipArr;
      //验证IP和IP段
      this.ipformData();
    },

接下来验证IP或IP段是否 正确

 // ip一键格式化
    ipformData() {
    //提交创建状态(可以删除,我的项目用到了)
      this.formIP = true;
      this.charIp = [];
      let ip = [];
      let errorIp = [];
      this.ipArr.forEach((item) => {
        // console.log(item);
        // 判断ip不是空
        if (item != "") {
          // 先判断是否是正常的ip 如果不是 判断是否是IP段
          if (this.isValidIP(item)) {
            // 如果是正常IP添加到数组
            ip.push(item);
          } else {
            // 不是正常IP验证是否是IP段
            // console.log(this.isValidIPs(item));
            if (this.isValidIPs(item)) {
              // 如果是IP段添加数组

              ip.push(item);
            } else {
              // 不是IP段添加到错误的IP数组
              errorIp.push(item);
            }
          }
        } else {
        }
      });
      // console.log(errorIp);
      // console.log(ip);

      this.processingIp = ip;

      this.errorIp = errorIp;

      // 如果有错误IP显示错误提示
      if (errorIp.length > 0) {
        this.ipState = true;
        //这个换行 是结果放在头部 提醒用户 IP不正确
        errorIp.push("\n");
        errorIp.push("\n");
      } else {
        this.ipState = false;
      }
      //每隔一行换行
      ip.forEach((item, index) => {
        this.charIp.push(item + "," + "\n");
      });
      if (errorIp.length > 0) {
        this.charIp.unshift(errorIp);
      }
      // console.log(this.charIp.join(""));
      var reg = /,$/gi;
      this.formData.ip = this.charIp
        .join("")
        .replace(reg, "")
        .replace(/,/g, "");
      // console.log(this.formData.ip);
    },

然后就是IP和IP段的校验

    // IP正则
    isValidIP(ip) {
      var reg =
        /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
      return reg.test(ip);
    },

    // IP段正则(可以是-也可以是/)
    isValidIPs(ip) {
      var reg =
        /^(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\/|\-([1-9]|[1-2]\d|3[0-2])$/;
      return reg.test(ip);
    },
0

评论 (0)

取消