Vue js IP批量格式化

最近遇到个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);
    },

Blog原文章

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值