Skip to content

Instantly share code, notes, and snippets.

@mtimbs
Last active August 29, 2020 12:43
Show Gist options
  • Save mtimbs/cd448043ce5d2833f07584de7f34453a to your computer and use it in GitHub Desktop.
Save mtimbs/cd448043ce5d2833f07584de7f34453a to your computer and use it in GitHub Desktop.
IP4 validation
// Using Loops (and Regex)
const validateIP = ip => {
const regex = /^\d+$/;
const s = IP.split('.');
if(s.length !== 4) return false;
for(let i = 0; i < s.length; i++) {
if(!regex.test(s[i])) return false;
if(s[i].length > 1 && s[i].startsWith('0')) return false;
const n = parseInt(s[i]);
if(Number.isNaN(n)) return false;
if(n < 0 || n > 255) return false;
}
return 'IPv4';
}
// Using a filter and map
const validRange = (n: number): boolean => n >= 0 && n <= 255;
const validateIP = (ip: string): boolean => {
const numbers: string[] = ip.split('.');
return numbers.length === 4
&& numbers
.filter((x) => Number(x).toString() === x) // remove any numbers with leading 0s
.map((x) => parseInt(x, 10)) // convert to number
.filter(validRange) // filter out invalid range
.length === 4; // check we still have 4 numbers
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment