vili said:
hello!
can somebody clear what does line 2 and line3 mean??
thanx!
function isValidIPAddress(ipaddr) {
var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; this line
That creates a regular expression called 're' that will match a string
starting with 1 to 3 digits, then a period '.', 1 to 3 digits, then a
period, 1 to 3 digits, then a period, then 1 to 3 digits at the end.
It appears to match the pattern of an IP address, e.g. 192.168.1.1. It
will also match 999.0.80.888 and many others.
That tests if the pattern appears in the value of the variable 'ipaddr'
var parts = ipaddr.split(".");
This will create an array 'parts' that is the elements of ipaddr when
split using a period '.'.
if (parseInt(parseFloat(parts[0])) == 0) { return false; }
That would appear redundant, since the previous test has already
determined that the elements of 'parts' will only consist of digits, and
that any number will be an integer. A simpler test is:
if ( parts[0] == '0') { return false; }
for (var i=0; i<parts.length; i++) {
if (parseInt(parseFloat(parts)) > 255) { return false; }
Again, parseInt & parseFloat here are redundant:
if ( parts > 255 ) { return false; }
If you want to be explicit about it, convert parts to a number (but
it isn't necessary):
if ( +parts > 255 ) { return false; }
}
return true;
} else {
return false;
}
}
A more concise (though perhaps more obfuscated) test is:
function isValidIPv4Addr(ipaddr)
{
var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
if ( !re.test(ipaddr) ) { return false; }
var parts = ipaddr.split('.');
return (parts[0] != 0 && parts[0] <= 255)
&& parts[1] <= 255
&& parts[2] <= 255
&& parts[3] <= 255;
}
I am no expert on IP addresses, but it seems that '0' is valid as the
first component of the address, I don't know why the test discounts it.
The scheme also only matches an IP version 4 address and will not match
the new IP version 6 addresses[1], so perhaps the function should be
called 'isValidIPv4Address'.
1. <URL: http://en.wikipedia.org/wiki/IPv6 >