Add isValidIpv4

Signed-off-by: Mcat12 <newtoncat12@yahoo.com>
This commit is contained in:
Mcat12
2018-11-05 11:54:52 -05:00
parent cd53df4b96
commit bc12f17e1e
2 changed files with 58 additions and 0 deletions
+23
View File
@@ -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));
}
+35
View File
@@ -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);
});
});
});