Search code examples
javaurl-validation

UrlValidator is not working for localhost


I'm facing an issue that i'm using UrlValidator in my code.

UrlValidator urlValidator = UrlValidator.getInstance();
    if(urlValidator.isValid(url)) {
        throw new IllegalArgumentException( url + "not valid");
    }
 where url i'm passing is 

 [1]: http://localhost:8080/myapp/Education.html

.I'm getting IllegalArgumentException n if i'm passing url i.e

 [2]: https://www.google.co.in/

its working fine.How to make this code working for localhost:8080


Solution

  • if you take a look at the documentation you'll have a hint on how to accept local urls

    For example

    public class Validator {
        public static void main(String[] args) {
            UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
            if (urlValidator.isValid("http://localhost/page.htm")) {
                System.out.println("Valid URL");
            }
            else {
                System.out.println("Invalid URL");
            }
    
        }
    
    }
    

    it will output

    Valid URL