Any IP address has to fall into [0-255].[0-255].[0-255].[0-255] format criteria.
We can achieve this by using following 2 ways.
Using split method of String: The method described above can also be written in a simple way as follows
public boolean validateIPAddress( String ipAddress ) {
String[] tokens = ipAddress.split("\\.");
if (tokens.length != 4) {
return false;
}
for (String str : tokens) {
int i = 0;
try {
i = Integer.parseInt( s );
} catch (NumberFormatException e) { //if any character data is entered.
return false;
}
if ((i < 0) || (i > 255)) {
return false;
}
}
return true;
}
Using regular expression: The following method with return true is the IP Address is valid, else it returns false.
public boolean validateIPAddress( String ipAddress ){
final Pattern ipAdd= Pattern.compile("b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
+ "{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)b");
return ipAdd.matcher(ipAddress).matches();
}
If it's is false, we can show error message as "IP Address must be in the in the format of: [0-255].[0-255].[0-255].[0-255]"
We can achieve this by using following 2 ways.
Using split method of String: The method described above can also be written in a simple way as follows
public boolean validateIPAddress( String ipAddress ) {
String[] tokens = ipAddress.split("\\.");
if (tokens.length != 4) {
return false;
}
for (String str : tokens) {
int i = 0;
try {
i = Integer.parseInt( s );
} catch (NumberFormatException e) { //if any character data is entered.
return false;
}
if ((i < 0) || (i > 255)) {
return false;
}
}
return true;
}
Using regular expression: The following method with return true is the IP Address is valid, else it returns false.
public boolean validateIPAddress( String ipAddress ){
final Pattern ipAdd= Pattern.compile("b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
+ "{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)b");
return ipAdd.matcher(ipAddress).matches();
}
If it's is false, we can show error message as "IP Address must be in the in the format of: [0-255].[0-255].[0-255].[0-255]"
No comments:
Post a Comment