You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需正则表达式,使用JavaScript验证逗号分隔的多个IP地址

No-Regex IP List Validation in JavaScript

Got it, let's build a regex-free solution to validate your comma-separated IP list. This approach will manually check each IP segment to ensure it meets the format and value requirements.

Step-by-Step Solution

First, we'll split the input into individual IPs, then validate each one by breaking it down into its four segments and checking each segment's validity.

function validateIPList(input) {
    // Trim whitespace and split into individual IPs, filter out empty entries
    const ipList = input.trim().split(',').map(ip => ip.trim()).filter(ip => ip.length > 0);
    
    // Validate each IP in the list
    for (const ip of ipList) {
        if (!validateSingleIP(ip)) {
            return false;
        }
    }
    return true;
}

function validateSingleIP(ip) {
    const segments = ip.split('.');
    
    // Must have exactly 4 segments
    if (segments.length !== 4) {
        return false;
    }
    
    for (const segment of segments) {
        // Segment can't be empty or contain non-numeric characters
        if (segment.length === 0 || isNaN(Number(segment))) {
            return false;
        }
        
        const num = Number(segment);
        // Segment must be an integer between 0 and 255 inclusive
        if (!Number.isInteger(num) || num < 0 || num > 255) {
            return false;
        }
        
        // Optional: Disallow leading zeros (uncomment if needed)
        // if (segment.length > 1 && segment.startsWith('0')) {
        //     return false;
        // }
    }
    
    return true;
}

// Example usage:
const testInput = "1.1.1.1,2.2.2.2,3.3.3.,4.4.4.256";
console.log(validateIPList(testInput)); // Returns false (invalid segments in 3rd and 4th IPs)

How It Works

  • Input Handling: We first clean the input by trimming whitespace, splitting on commas, and removing any empty entries (from accidental extra commas).
  • Single IP Validation:
    • Split the IP into 4 segments using the dot character. If there aren't exactly 4 segments, it's invalid.
    • For each segment:
      • Ensure it's not empty and contains only numeric characters.
      • Convert the segment to a number and check if it's an integer between 0 and 255.
      • Optional: Uncomment the leading zero check if you want to disallow IPs like 010.0.0.1 (though technically valid in IPv4, some systems prefer no leading zeros).

Testing the Function

Using your example input "1.1.1.1,2.2.2.2,3.3.3.,4.4.4.256", the function will return false because:

  • The third IP (3.3.3.) has an empty fourth segment.
  • The fourth IP (4.4.4.256) has a segment value greater than 255.

内容的提问来源于stack exchange,提问作者tonyf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:59:03