Reputation: 33
I used this pattern to check whether a field's form is an IP address:
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[i];
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;
}
if (thisSegment.toString() == "*")
errorString = "";
}
}
extensionLength = 3;
if (errorString == "")
alert ("That is a valid IP address.");
else
alert (errorString);
}
}
But I need to account for the value of the field having an octet(s) with an asterisk '*' or a range '0-255'.
Like for example:
192.168.1.1 --> It will be OK
192.168.*.* --> It will be OK
192.168.2-3.0-128 --> It will be OK
192.168.2-3.* --> It will be OK
Any ideas? Thank you so much!
Upvotes: 3
Views: 1053
Reputation: 8938
For the specific input strings you provided, start with the following:
^(\d{1,3})\.(\d{1,3})\.(\*|(?:\d{1,3}(?:-\d{1,3})?))\.(\*|(?:\d{1,3}(?:-\d{1,3})?))$
In your JavaScript, this would become:
var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\*|(?:\d{1,3}(?:-\d{1,3})?))\.(\*|(?:\d{1,3}(?:-\d{1,3})?))$/;
You can further eliminate repetition in the pattern of course, but that will make the evolution from what you provided to start even less clear: start with a more verbose, repetitive pattern; get solid positive and negative tests in place; and then refactor to eliminate repetition as needed/desired.
Upvotes: 3
Reputation: 1684
There are at least two issues here:
Your regex should match asterisks in the allowed positions. See regex from J0e3gan's answer.
You are looping through indexes 0-3 of the array returned by match
. match
returns the full string in index 0 and each segment in the following indexes. Therefore, your for loop should be as follows: for (i = 1; i <= 4; i++) { // processing }
.
Upvotes: 0