3

How to check if the URL is valid or not. Patterns.WEB_URL.matcher(urlString).matches() returns false for android version 5 and below. Also ,various links say URLUtil.isValidUrl(urlString) is not good to use.

stack Learner
  • 1,318
  • 3
  • 18
  • 35
  • 3
    Possible duplicate of [How to check if URL is valid in Android](https://stackoverflow.com/questions/4905075/how-to-check-if-url-is-valid-in-android) – ADM Dec 01 '17 at 06:25

4 Answers4

8

Shouldn't use URLUtil to validate the URL as below.

URLUtil.isValidUrl(url)

because it gives strings like "http://" as valid URL which isn't true

Better way is

Patterns.WEB_URL.matcher(potentialUrl).matches()

It will return True if URL is valid and false if URL is invalid.

EKN
  • 1,886
  • 1
  • 16
  • 29
2

Your Solution is:

URLUtil.isValidUrl(url);

or You can use if above code doesnt work.

Patterns.WEB_URL.matcher(url).matches();
1

You can check Url is valid or not using two methods

  1. URLUtil.isValidUrl(url)

    Problem is : it return true for "http://" which is wrong

  2. Second way is

    Patterns.WEB_URL.matcher(potentialUrl).matches();

Community
  • 1
  • 1
Zealous System
  • 2,080
  • 11
  • 22
1

Or you can use combination of both:)

fun isUrlValid(url: String?): Boolean {
        url ?: return false
        return Patterns.WEB_URL.matcher(url).matches() && URLUtil.isValidUrl(url)
    }
NataTse
  • 381
  • 2
  • 10