stack Learner
stack Learner

Reputation: 1348

How to check if the URL is valid in android?

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.

Upvotes: 3

Views: 7394

Answers (4)

NataTse
NataTse

Reputation: 411

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)
    }

Upvotes: 1

Zealous System
Zealous System

Reputation: 2324

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();

Upvotes: 1

EKN
EKN

Reputation: 1914

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.

Upvotes: 8

Dhaval Kasundra
Dhaval Kasundra

Reputation: 61

Your Solution is:

URLUtil.isValidUrl(url);

or You can use if above code doesnt work.

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

Upvotes: 2

Related Questions