From bc12f17e1e57bbc2e4f72cf41014c54fec8cfddf Mon Sep 17 00:00:00 2001 From: Mcat12 Date: Mon, 5 Nov 2018 11:54:52 -0500 Subject: [PATCH] Add isValidIpv4 Signed-off-by: Mcat12 --- src/validate.js | 23 +++++++++++++++++++++++ src/validate.test.js | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/validate.js b/src/validate.js index 096ccb1..6124190 100644 --- a/src/validate.js +++ b/src/validate.js @@ -50,3 +50,26 @@ export function isValidRegex(regex) { } return true; } + +/** + * Check if the string is a valid IPv4 address + * + * @param address {string} the address to check + * @returns {boolean} if the address is a valid IPv4 address + */ +export function isValidIpv4(address) { + const segments = address.split("."); + + // Must have 4 segments + if (segments.length !== 4) { + return false; + } + + // No segment can be longer than 3 characters or be empty + if (segments.some(segment => segment.length > 3 || segment.length === 0)) { + return false; + } + + // All segments must be numbers (positive) + return segments.every(segment => isStrictPositiveNumber(segment)); +} diff --git a/src/validate.test.js b/src/validate.test.js index b16d1d3..12ca7e5 100644 --- a/src/validate.test.js +++ b/src/validate.test.js @@ -11,6 +11,7 @@ import { isStrictPositiveNumber, isValidDomain, + isValidIpv4, isValidRegex } from "./validate"; @@ -149,4 +150,38 @@ describe("Testing the validation functions", () => { expect(isValidRegex("[0-")).toBe(false); }); }); + + describe("isValidIpv4", () => { + it("passes 127.0.0.1", () => { + expect(isValidIpv4("127.0.0.1")).toBe(true); + }); + + it("passes 1.1.1.1", () => { + expect(isValidIpv4("1.1.1.1")).toBe(true); + }); + + it("passes 111.111.111.111", () => { + expect(isValidIpv4("111.111.111.111")).toBe(true); + }); + + it("fails 1111.1.1.1", () => { + expect(isValidIpv4("1111.1.1.1")).toBe(false); + }); + + it("fails 1.1.1.", () => { + expect(isValidIpv4("1.1.1.")).toBe(false); + }); + + it("fails empty string", () => { + expect(isValidIpv4("")).toBe(false); + }); + + it("fails 8.8", () => { + expect(isValidIpv4("8.8")).toBe(false); + }); + + it("fails 10. 10.1.1", () => { + expect(isValidIpv4("10. 10.1.1")).toBe(false); + }); + }); });