BAEL-6049-validate-ipv4-address (#13287)

* validate ipv4

* add unit test

* add more unit tests

* add more unit tests

* add more unit test

---------

Co-authored-by: tienvn4 <tienvn4@ghtk.co>
This commit is contained in:
vunamtien
2023-02-07 01:54:29 +07:00
committed by GitHub
parent 87c22e5be4
commit ebd6a0e73a
2 changed files with 148 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
package com.baeldung.urlvalidation;
import com.google.common.net.InetAddresses;
import org.apache.commons.validator.routines.InetAddressValidator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPv4Validation {
public static boolean validateWithApacheCommons(String ip) {
InetAddressValidator validator = InetAddressValidator.getInstance();
return validator.isValid(ip);
}
public static boolean validateWithGuava(String ip) {
return InetAddresses.isInetAddress(ip);
}
public static boolean validateWithRegex(String ip) {
String regex = "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
}
}