How to validate URL in Java

A short example to show the use of apache.commons.validator.UrlValidator class to validate an URL in Java.


import org.apache.commons.validator.UrlValidator;

public class ValidateUrlExample{
	
	public static void main(String[] args) {
		
	    UrlValidator urlValidator = new UrlValidator();
		
	    //valid URL
	    if (urlValidator.isValid("https://mkyong.com")) {
	       System.out.println("url is valid");
	    } else {
	       System.out.println("url is invalid");
	    }

	    //invalid URL
	    if (urlValidator.isValid("http://invalidURL^$&%$&^")) {
	        System.out.println("url is valid");
	    } else {
	        System.out.println("url is invalid");
	    }
	    
	}
}

Output


url is valid
url is invalid

Reference

  1. http://commons.apache.org/validator/apidocs/org/apache/commons/validator/UrlValidator.html

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Armando
15 years ago

urlValidator.isValid(“www.mkyong.com”)
***** url is invalid 🙁 ****

Thor Wehage
15 years ago

Looks pretty easy to use.
I can’t figure out how to include it as a dependency in maven. Do you happen to know how ?

Like in (lorem ipsum data) :

org.apache.commons
validator
1.1.1

best regards,
Thor

Hussain A Wahid
13 years ago
Reply to  mkyong

Hi ,
I executed the exact code using downloading the jar from http://mirrors.ibiblio.org/maven2/commons-validator/commons-validator/1.1.0/commons-validator-1.1.0.jar

but it fails for both the URL , validates nothing

Hugo
13 years ago

I don’t know if you’re having this problem yet.
But, verify the jar’s version. I’ve downloaded the 1.1.0 and the code didn’t work too.
Then, I’ve tried the 1.3.1 and it worked fine.

pat
5 years ago

and yet “.com” is a valid url? or even “:80” ?

Vitalii
7 years ago

ctrl+c ctrl+v from source docs, very helpful

gjr
10 years ago

is this valid url – http://mail.go

this code returns invalid in commons-validator:jar:1.4.1
and i am sure there are more like this..

sandesh
11 years ago

This is also possible using jsoup and json.If we use this we can have customized validation like validating the java script for url ,validate url for pagination , validate url for color swatches etc

Tawkeer hussain
13 years ago

It works…thanks

Hussain A Wahid
13 years ago

Hi ,
I executed the exact code using downloading the jar from http://mirrors.ibiblio.org/maven2/commons-validator/commons-validator/1.1.0/commons-validator-1.1.0.jar

but it fails for both the URL , validates nothing

Satish Sharma
13 years ago

Is there any way to customize UrlValidator so that “www.mkyong.com” can be validated? I want to validate some url which does not have protocols. like:
http://www.mkyong.com

Thor Wehage
15 years ago

thanx 🙂