I have a method that validates a user-written IP address in an Android application. If it's invalid, I need to know why and notify the user using a Toast
.
I created an enum for this called Status
that has a list of reasons for an IP address to be invalid and a value for when it's valid. The method isValid
will return a Status
value depending on whether or not it's invalid.
Android code
switch(IP.isValid(ip.getText().toString())) {
case INVALID_NUMBER:
Toast.makeText(MainActivity.this, "You have entered an invalid octect(s) value", Toast.LENGTH_SHORT).show();
break;
case INVALID_LENGTH:
Toast.makeText(MainActivity.this, "You have entered an IP with an invalid length", Toast.LENGTH_SHORT).show();
break;
case NON_NUMERIC:
Toast.makeText(MainActivity.this, "You have entered a non-numeric IP", Toast.LENGTH_SHORT).show();
break;
}
ip
is anEditText
field.
Status
enum
public enum Status {
INVALID_NUMBER,
INVALID_LENGTH,
NON_NUMERIC,
VALID
}
isValid()
method
public static Status isValid(String ip) {
String[] octets = ip.split("\\.");
if(octets.length != 4) {
return Status.INVALID_LENGTH;
}
for(String octet : octets) {
if(StringUtils.isNumeric(octet)) {
int val = Integer.parseInt(octet);
if(val > 255 || val < 0) {
return Status.INVALID_NUMBER;
}
} else {
return Status.NON_NUMERIC;
}
}
return Status.VALID;
}
StringUtils.isNumeric()
(StringUtils
is a class I created, it's not from Apache)
https://stackoverflow.com/a/237204/4355066
public static boolean isNumeric(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
Is this the best way to this?