Home > other >  How do I validate a URL such as "http://mylocalhost:port "in Java?
How do I validate a URL such as "http://mylocalhost:port "in Java?

Time:08-19

I want to validate that a URL entered by a user in a given server must be in this format. for example http://localhost:port only. If the URL port is followed by any other strings or anything like this "http://localhost:port/anything ", it should be regarded as an invalid URL. How can I do this with Regex? I have tried this:

public boolean isValidUrl(String url){
    try{
        return new URL(url).toURI();
    }catch(MalformedURLException ex){
        log.info(INVALID_URL_MESSAGE, url)
        return false
    }
}

But this allows other strings after the port number

CodePudding user response:

You can test by looking at the result of the methods on the URL

public boolean isValidUrl(String url){
    try{
        URL myURL = new URL(url);
        // only return true if path and query bits are empty
        return myURL.getPath() == null && myURL.getQuery() == null;
    }catch(MalformedURLException ex){
        log.info(INVALID_URL_MESSAGE, url)
        return false
    }
}
  • Related