JavaScript - Check if a String is a Valid IP Address Format
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 types of IP addresses: IPv4 and IPv6. In this article, we’ll explore how to check if a string is a valid IP address format in JavaScript.
Using Regular Expressions
This approach uses regular expressions to match valid IPv4 and IPv6 patterns.
function checkIp(ip) {
const ipv4 =
/^(\d{1,3}\.){3}\d{1,3}$/;
const ipv6 =
/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
return ipv4.test(ip) || ipv6.test(ip);
}
const ipAddress = "122.0.0.0";
console.log(checkIp(ipAddress));
Output
true
Using Split and Validate
This approach splits the string by periods or colons and validates each part individually.
function validIp(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(validIp(ipAddress));
Output
true
Using Library Functions
There are some libraries available in JavaScript that make IP address validation easier. One popular library is ip-address
. This library helps to easily check whether an IP address is valid.
First, install the library
npm install ip-address
const ip = require('ip-address');
function checkIp(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(checkIp(ipAddress));
Output
true
Using 'net' module (Node.js specific)
If you are using Node.js, you can use the built-in net module to check if an IP address is valid. The net module provides functions like is IPv4() and is IPv6() to check if the address is valid.
const net = require('net');
function isValidIp(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(isValidIp(ipAddress));
Output
true