47 lines
1.3 KiB
TypeScript
47 lines
1.3 KiB
TypeScript
export function validv4(ipaddress: string): boolean {
|
|
if (
|
|
/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(
|
|
ipaddress,
|
|
)
|
|
) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
export function validv6(value: string): boolean {
|
|
// See https://blogs.msdn.microsoft.com/oldnewthing/20060522-08/?p=31113 and
|
|
// https://4sysops.com/archives/ipv6-tutorial-part-4-ipv6-address-syntax/
|
|
const components = value.split(':');
|
|
if (components.length < 2 || components.length > 8) {
|
|
return false;
|
|
}
|
|
|
|
if (components[0] !== '' || components[1] !== '') {
|
|
// Address does not begin with a zero compression ("::")
|
|
if (!components[0].match(/^[\da-f]{1,4}/i)) {
|
|
// Component must contain 1-4 hex characters
|
|
return false;
|
|
}
|
|
}
|
|
|
|
let numberOfZeroCompressions = 0;
|
|
for (let i = 1; i < components.length; ++i) {
|
|
if (components[i] === '') {
|
|
// We're inside a zero compression ("::")
|
|
++numberOfZeroCompressions;
|
|
if (numberOfZeroCompressions > 1) {
|
|
// Zero compression can only occur once in an address
|
|
return false;
|
|
}
|
|
continue;
|
|
}
|
|
if (!components[i].match(/^[\da-f]{1,4}/i)) {
|
|
// Component must contain 1-4 hex characters
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|