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.
Asked
Active
Viewed 6,611 times
3

Harshad Prajapati
- 820
- 8
- 14

stack Learner
- 1,318
- 3
- 18
- 35
-
3Possible 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 Answers
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();

Dhaval Kasundra
- 61
- 2
-
the below code didn't care about "http://" so I used the top one, thanks. – fullmoon Aug 05 '18 at 20:00
1
You can check Url is valid or not using two methods
URLUtil.isValidUrl(url)
Problem is : it return true for "http://" which is wrong
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