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("http://www.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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Tawkeer hussain

    It works…thanks

  • http://facebookprofile Hussain A Wahid

    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

    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

  • Armando

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

  • http://kiteboarding.dk Thor Wehage

    thanx :)

  • http://kiteboarding.dk Thor Wehage

    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

    • http://www.mkyong.com mkyong

      Get it from Maven central repository, you may need the Jakarta oro.jar as well.

         <dependency>
      	  	<groupId>commons-validator</groupId>
      		<artifactId>commons-validator</artifactId>
      		<version>1.3.1</version>
         </dependency>
       
         <dependency>
      		<groupId>oro</groupId>
      		<artifactId>oro</artifactId>
      		<version>2.0.8</version>
         </dependency>