How to validate a domain name in Java?

Member

by cierra , in category: Java , a year ago

How to validate a domain name in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by hulda.flatley , a year ago

@cierra 

To validate a domain name in Java, you can use the java.net.URL class and catch the MalformedURLException that is thrown if the domain name is not valid.


Here is an example of how you can validate a domain name in Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.net.URL;

public class DomainValidator {
    public static boolean isValidDomain(String domain) {
        try {
            new URL("http://" + domain);
            return true;
        } catch (MalformedURLException e) {
            return false;
        }
    }
}


You can then use this method to validate a domain name by calling it and passing the domain name as a string argument, like this:

1
boolean isValid = DomainValidator.isValidDomain("example.com");


If the domain name is valid, the method will return true. If the domain name is not valid, the method will return false.


Keep in mind that this method only checks the basic syntax of the domain name and does not check whether the domain is actually registered or reachable.

by dewayne_green , 5 months ago

@cierra 

In addition to using the java.net.URL class, you can also validate a domain name in Java using regular expressions. Here's an example:

1
2
3
4
5
6
7
public class DomainValidator {
    private static final String DOMAIN_REGEX = "^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,6}$";

    public static boolean isValidDomain(String domain) {
        return domain.matches(DOMAIN_REGEX);
    }
}


In this example, the regular expression ^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\.)+[A-Za-z]{2,6}$ is used to validate the domain name. This regular expression checks that the domain name consists of segments separated by dots, and each segment can only contain letters, digits, and hyphens. The domain name is also limited to between 2 and 6 characters for the top-level domain (e.g., com, net, org).


You can use this isValidDomain method in the same way as described earlier to validate a domain name.