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