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){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))/;
不同IP换行(回车)输入
validator = (rule, value, callback) => {
if (!value) {
callback();
}
// value = value.replace(/\;/g, ',');
// value = value.replace(/\;/g, ',');
// value = value.replace(/\,/g, ',');
// value = value.replace(/\s+/g, ',');
// value = value.replace(/\n/g, '');
value = value.split('\n');
console.log(value, 'val-----')
value = value.filter(item => item);
const errorIp = value.filter((item) => {
if (item[0] == '!') {
item = item.substring(1, item.length);
}
if (item.indexOf('/') > -1) {
return !new RegExp(ipReg).test(item) || (!item.split('/')[1]) || isNaN(Number(item.split('/')[1]));
} else if (item.indexOf('-') > -1) {
return !new RegExp(ipReg).test(item) || (!item.split('-')[1]) || isNaN(Number(item.split('-')[1]));
}
//踩雷,这种写法,如果||第一个条件不满足,就回走else,这个和||的基础语法有关
// else if (( item.indexOf('$') || item.indexOf('@') || item.indexOf(',') || item.indexOf(';') || item.indexOf(';') || item.indexOf(',')) > -1) {
// callback('IP请换行输入');
// }
else if ((item.indexOf(' ')) > -1 || item.indexOf('@') > -1 || item.indexOf(',') > -1 || item.indexOf(',') > -1 || item.indexOf(';') > -1 || item.indexOf(';') > -1 || item.indexOf('$') > -1) {
callback('IP请换行输入');
}
else {
return !new RegExp(ipReg).test(item);
}
});
if (errorIp.length > 0) {
callback('请输入正确的IP');
}
callback();
}
在form中的使用:
<FormItem label="" style={{ marginBottom: 10 }}>
{form.getFieldDecorator("IP", {
rules: [
{ required: true, message: "请输入IP" },
{ validator: this.validator },
],
})(
<Input.TextArea
style={{ width: '580px', height: 260 }}
/>
)}
</FormItem>
补充:刚刚在网上看到了好的IPV4和IPV6校验,感觉很有用,上链接:https://www.w3cschool.cn/notebook/notebook-jghl2tn5.html