4

Does someone knows a function that validate if a url is valid or not purely in GWT java without using any JSNI

Noor
  • 19,638
  • 38
  • 136
  • 254

3 Answers3

10

I am using this one (making use of regular expressions):

private RegExp urlValidator;
private RegExp urlPlusTldValidator;
public boolean isValidUrl(String url, boolean topLevelDomainRequired) {
    if (urlValidator == null || urlPlusTldValidator == null) {
        urlValidator = RegExp.compile("^((ftp|http|https)://[\\w@.\\-\\_]+(:\\d{1,5})?(/[\\w#!:.?+=&%@!\\_\\-/]+)*){1}$");
        urlPlusTldValidator = RegExp.compile("^((ftp|http|https)://[\\w@.\\-\\_]+\\.[a-zA-Z]{2,}(:\\d{1,5})?(/[\\w#!:.?+=&%@!\\_\\-/]+)*){1}$");
    }
    return (topLevelDomainRequired ? urlPlusTldValidator : urlValidator).exec(url) != null;
}
svub
  • 124
  • 5
  • I find this doesn't validate URLs with a trailing slash like 'http://google.com/' – Andy Smith Sep 29 '12 at 12:11
  • @Andy: just wrote a small JUnit and indeed it returns false on `google.com/` -- but it does return true on `http://google.com/` (with or without trailing slash). According to the definition of URLs, the schema prefix (e.g. 'http') followed by `://` is mandatory, thus `google.com` is invalid. – svub Oct 25 '12 at 14:34
  • @Sven Ah, apologies, I was under the impression I was prepending `http://` but it's entirely possible that I forgot! (+1) – Andy Smith Oct 25 '12 at 15:25
  • How can I detect urls with params ? Something like : `https://xyz.com/getUser.action?id=1&pwd=2` – Sourabh Dec 03 '14 at 09:59
  • You could use the RegExp above to test for a valid URL first and then test if the URL also contains a "?" - that should be the simplest solution. Otherwise, you would need to take the "?" from the last, optional class ([...?...]+) and make it mandatory. – svub Dec 04 '14 at 23:40
0

org.apache.commons.validator.UrlValidator and static method isValid(String url) might be of help here.

Anton K.
  • 933
  • 3
  • 9
  • 22
0

You should use regular expression in GWT. Here is similar topics Regex in GWT to match URLs and Regular Expressions and GWT

Community
  • 1
  • 1