Just thoughts

Friday, May 21, 2010

Validating an URL in Java

Short and to the point. You can do it in two ways: hard and simple. Hard is when you come up with a 600 byte long regex pattern and your pattern fails when your user inputs something you haven't thought of, or you can go the simple way and test if the URL is reachable from java.net's point of view. If it's not, you can't use it anyway.

Java.net throws an exception if the URL isn't valid, but you don't have to use the thrown message, who said you have to?
//...
import java.net.MalformedURLException;
import java.net.URL;
//...

private boolean isValidURL(String a) {
        try {
            URL url = new URL(a);
            return true;
        } catch (MalformedURLException e) {
            return false;
        }
}

The usage is... very simple:

if(isValidURL(userInput)){
     //Do something
}else{
    // URL is invalid
}

I Googled quite a lot for a better way which is simpleminded like me but no luck. So that method is actually as simple as my mind...

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home