需求:
validateAddress(address) {
const parts = address.split(':'); //例子:['192.168.0.55', '2022']
const host = parts[0];
const port = Number(parts[1]);
if (/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test(host)) {
// 是 IP 地址
const octets = host.split('.');
if (octets.length !== 4) {
return 'IP地址格式错误';
}
for (let i = 0; i < octets.length; i++) {
const octet = Number(octets[i]);
if (isNaN(octet) || octet < 0 || octet > 255) {
return 'IP地址范围[0,255]';
}
}
if (isNaN(port) || port < 0 || port > 65535) {
return '端口取值范围(0,65535)';
}
return '';
} else if (/^[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/.test(host)) {
// 是域名
const domainRegex = /^[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)+$/;
if (!domainRegex.test(host)) {
return '域名格式错误';
}
const parts = host.split('.');
if (host.length > 253) {
return '域名长度不能超过253个字符';
}
if (parts.length < 2 || parts[parts.length - 1].length < 2) {
return '顶级域名长度大于2字符';
}
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.length > 63) {
return '每个部分的长度不能超过63个字符';
}
}
return '';
} else {
return '地址格式错误';
}
},
validateAddresses(addresses) {
let valid = true;
const messages = [];
for (let i = 0; i < addresses.length; i++) {
const address = addresses[i];
const message = this.validateAddress(address);
if (message) {
valid = false;
messages.push(`第${i + 1}行:${message}`);
}
}
if (!valid) {
return messages.join('\n');
}
return '地址格式正确';
},
// 测试地址格式
const addresses = this.dataSourceForm.host.split('\n');
console.log(this.validateAddresses(addresses)); // 输出:第2行:域名格式错误\n第3行:地址格式错误
if (this.validateAddresses(addresses) === '地址格式正确') {
console.log('成功啦');
// 你的操作逻辑----
} else {
console.log('失败咯');
this.$message.error(this.validateAddresses(addresses))
}