verifyIP javascript problem

admin

Administrator
Staff member
Greetings All:

I have been using a javascript that verifies that the value entered in a text input field is a valid dotted decimal ip address. I found this "verifyIP" javascript at:

<!-- m --><a class="postlink" href="http://javascript.internet.com/forms/val-ip.html">http://javascript.internet.com/forms/val-ip.html</a><!-- m -->

I just found that the script has a problem. Although each dotted decimal segment of the ip address is checked that it is not >255, the script still allows three digit values above 255 in the last segment. For example:

1.1.1.256 to 1.1.1.999

I have tried this script with IE 6.0, 5.5, NetScape 7.0, and Mozilla 1.2.1.

I have looked at the script and do not see the problem. But I am still quite new to javascripting. Pershaps someone with much more experience can enlighten me about what is wrong and how to fix it?

The script source is available at the above link, where it can also be tested. I have copied the source below, for completeness.

Thanks in advance for any help!

<SCRIPT LANGUAGE="JavaScript">
<!-- Original: Jay Bienvenu -->
<!-- Web Site: <!-- m --><a class="postlink" href="http://www.bienvenu.net">http://www.bienvenu.net</a><!-- m --> -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! <!-- m --><a class="postlink" href="http://javascript.internet.com">http://javascript.internet.com</a><!-- m --> -->

<!-- Begin
function verifyIP (IPvalue) {
errorString = "";
theName = "IPaddress";

var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
var ipArray = IPvalue.match(ipPattern);

if (IPvalue == "0.0.0.0")
errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
else if (IPvalue == "255.255.255.255")
errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
if (ipArray == null)
errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
else {
for (i = 0; i < 4; i++) {
thisSegment = ipArray;
if (thisSegment > 255) {
errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
i = 4;
}
if ((i == 0) && (thisSegment > 255)) {
errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
i = 4;
}
}
}
extensionLength = 3;
if (errorString == "")
alert ("That is a valid IP address.");
else
alert (errorString);
}
// End -->
</script>
 
Back
Top