How to check if a string is a valid IP address format in JavaScript ?

In this article, we will see how to check if a string is a valid IP address or not. An IP address is a unique identifier assigned to each device connected to a computer network that uses the Internet Protocol for communication. There are two common formats for IP addresses: IPv4 and IPv6. Checking if a string is a valid IP address format in JavaScript involves verifying if the string follows the rules for a standard IPv4 or IPv6 address.

These are the methods to check if a string is a valid IP address format in JavaScript:

Table of Content

  • Using Split and Validate
  • Using Library Functions
  • Using net Module (Node.js specific):
  • Using Built-in Methods:

Using Regular Expressions

This approach uses regular expressions to match valid IPv4 and IPv6 patterns.

Example: This example uses the Regular Expressions to validate the IP address format for the String.

Javascript
function checkIpAddress(ip) {
    const ipv4Pattern = 
        /^(\d{1,3}\.){3}\d{1,3}$/;
    const ipv6Pattern = 
        /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
    return ipv4Pattern.test(ip) || ipv6Pattern.test(ip);
}
const ipAddress = "122.0.0.0";
console.log(checkIpAddress(ipAddress));

Output
true

Using Split and Validate

This approach splits the string by periods or colons and validates each part individually.

Example: This example describes the validation of IP address format for the string using Split and Validate.

Javascript
function validIpAddress(ip) {
    const parts = ip.split(/[.:]/);

    if (parts.length === 4) {

        // Check IPv4 parts
        for (const part of parts) {
            const num = parseInt(part);
            if (isNaN(num) || num < 0 || num > 255) {
                return false;
            }
        }
        return true;
    } else if (parts.length === 8) {

        // Check IPv6 parts
        for (const part of parts) {
            if (!/^[0-9a-fA-F]{1,4}$/.test(part)) {
                return false;
            }
        }
        return true;
    }
    return false;
}

const ipAddress = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
console.log(validIpAddress(ipAddress));

Output
true


Using Library Functions

Some JavaScript libraries provide functions to validate IP addresses. One such library is ip-address, which offers comprehensive IP address validation capabilities.

  • Install and use the ip-address library to validate IP addresses
const ip = require('ip-address');

Example: This example authenticating the validity of the IP address format of the String using the Library Functions.

Javascript
const ip = require('ip-address');

function checkIpAdress(ipAddress) {
    try {
        const parsed = new ip.Address6(ipAddress);
        return parsed.isValid() || new ip.Address4(ipAddress).isValid();
    } catch (e) {
        return false;
    }
}
const ipAddress = "192.168.1.1";
console.log(checkIpAdress(ipAddress)); 

Output:

true

Using net Module (Node.js specific):

Node.js provides the net module, which can be utilized to validate IP addresses as well.

Example:

JavaScript
const net = require('net');

function isValidIpAddress(ipAddress) {
    // For IPv4
    if (net.isIPv4(ipAddress)) {
        return true;
    }

    // For IPv6
    if (net.isIPv6(ipAddress)) {
        return true;
    }

    return false;
}

const ipAddress = "192.168.1.1";
console.log(isValidIpAddress(ipAddress));

Using Built-in Methods:

JavaScript’s built-in methods can also be utilized to check if a string is a valid IP address. One such method is inet_pton from the dns module. This method converts an IP address from its human-readable format (IPv4 or IPv6) into its binary form. By attempting to convert the string into binary format, we can determine if it’s a valid IP address.

Example:

JavaScript
const { promisify } = require('util');
const dns = require('dns');

// Promisify the dns.lookup method
const lookupPromise = promisify(dns.lookup);

// Function to check if a string is a valid IP address
async function isValidIPAddress(ipAddress) {
    try {
        // Attempt to convert the IP address to binary format
        await lookupPromise(ipAddress);
        return true; // If successful, it's a valid IP address
    } catch (error) {
        return false; // If an error occurs, it's not a valid IP address
    }
}

// Example usage
const ipAddress = '192.168.0.1';
isValidIPAddress(ipAddress).then(result => {
    console.log(result); // Output: true
});

Output:

true