dinesh707
dinesh707

Reputation: 12592

Why UrlValidator do not work for some of my Urls?

String[] schemes = {"http","https"};
UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_ALL_SCHEMES);
System.out.println(urlValidator.isValid(myUrl));

the following URL says, invalid. Any one know why is that. the localnet is a localnetwork. But this works for any other public network (it seems).

http://aunt.localnet/songs/barnbeat.ogg

Upvotes: 11

Views: 21684

Answers (7)

zmashiah
zmashiah

Reputation: 153

The library method fails on this URL:

  "http://en.wikipedia.org/wiki/3,2,1..._Frankie_Go_Boom"

Which is perfectly legal (and existing) URL.

I found by trial and error that the below code is more accurate:

public static boolean isValidURL(String url)
{
    URL u = null;
    try
    {
        u = new URL(url);
    }
    catch (MalformedURLException e)
    {
        return false;
    }

    try
    {
        u.toURI();
    }
    catch (URISyntaxException e)
    {  
        return false;  
    }  

    return true;  
}

Upvotes: 0

drchuck
drchuck

Reputation: 4675

This is fixed in the 1.4.1 release of the Apache Validator:

https://issues.apache.org/jira/browse/VALIDATOR-342 https://issues.apache.org/jira/browse/VALIDATOR/fixforversion/12320156

A simple upgrade to the latest version of the validator should fix things nicely.

Upvotes: 1

Armando Carrasco
Armando Carrasco

Reputation: 19

You can use the following:

UrlValidator urlValidator = new UrlValidator(schemes, new RegexValidator("^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$"), 0L);

Upvotes: 0

Quartz
Quartz

Reputation: 1851

The class you're using is deprecated. The replacement is

org.apache.commons.validator.routines.UrlValidator

Which is more flexible. You can pass the flag ALLOW_LOCAL_URLS to the constructor which would allow most addresses like the one you are using. In our case, we had authentication data preceeding the address, so we had to use the even-more-flexible UrlValidator(RegexValidator authorityValidator, long options) constructor.

Upvotes: 5

Qwerky
Qwerky

Reputation: 18445

As I thought, its failing on the top level;

String topLevel = domainSegment[segmentCount - 1];
if (topLevel.length() < 2 || topLevel.length() > 4) {
  return false;
}

your top level is localnet.

Upvotes: 4

Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

Here is the source code for isValid(String) method:

You can check the result at each step by manual call to understand where it fails.

Upvotes: 0

Mohamed Jameel
Mohamed Jameel

Reputation: 602

check line 2 it should be

new UrlValidator(schemes);

if you want to allow 2 slashes and disallow fragments

new UrlValidator(schemes, ALLOW_2_SLASHES + NO_FRAGMENTS);

Upvotes: 0

Related Questions