This technique can be used to validate URLs that don’t have a scheme.

I am using Apache Commons Validator for this.

private boolean _validateURL(final String URL) {
   String[] DEFAULT_SCHEMES = new String[]{"http", "https", "ftp"};
   UrlValidator validator = new UrlValidator(DEFAULT_SCHEMES) {
       /** allow missing scheme. */
       @Override
       public boolean isValid(String value) {
           return super.isValid(value) || super.isValid("http://" + value);
       }
   };
 
   return validator.isValid(URL);
}
Categories: JavaSnippets

2 Comments

Hien Gia · June 28, 2019 at 9:04 am

Hello,
Thank you for sharing.
Shouldn’t we use DEFAULT_SCHEMES inside the override method isValid() instead of hardcoding “http://”?

I mean:

final String[] DEFAULT_SCHEMES = new String[]{“http”, “https”, “ftp”};

and:

public boolean isValid(String value) {
boolean valid = super.isValid(value);
for(String scheme: DEFAULT_SCHEMES) {
valid = valid || super.isValid(scheme + “://” + value);
}
return valid;
}

    waqasaslam · July 17, 2019 at 2:17 am

    The util library already checks all of the schemes in DEFAULT_SCHEMES that we added, we do not need to loop through them. The purpose of this post is to validate the URL without a schema provided. This is why we have added the ‘or’ condition: … || super.isValid(“http://” + value);

    Over here we add any of the valid schemes if one wasn’t provided. Hope that makes sense!

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *