mirror of
https://github.com/gosticks/web.git
synced 2026-10-06 14:47:32 +00:00
@@ -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));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user