Skip to main content

How to check if a string is a valid URL in Kotlin

How to check if a string is a valid URL in Kotlin.

Here's a step-by-step tutorial on how to check if a string is a valid URL in Kotlin:

  1. Import the necessary classes:

    import java.net.URL
    import java.net.MalformedURLException
  2. Create a function that takes a string parameter for the URL and returns a boolean indicating whether it is valid or not:

    fun isValidUrl(urlString: String): Boolean {
    try {
    URL(urlString)
    return true
    } catch (e: MalformedURLException) {
    return false
    }
    }
  3. Call the isValidUrl function and pass the URL string as an argument to check if it is valid:

    val url = "https://www.example.com"
    val isValid = isValidUrl(url)
    println("Is $url a valid URL? $isValid")
  4. The URL constructor will throw a MalformedURLException if the URL string is not valid. So, we catch that exception and return false if it occurs.

  5. Here are a few additional examples to demonstrate the usage of the isValidUrl function:

    val url1 = "https://www.example.com"
    val isValid1 = isValidUrl(url1)
    println("Is $url1 a valid URL? $isValid1")

    val url2 = "ftp://ftp.example.com"
    val isValid2 = isValidUrl(url2)
    println("Is $url2 a valid URL? $isValid2")

    val url3 = "invalid-url"
    val isValid3 = isValidUrl(url3)
    println("Is $url3 a valid URL? $isValid3")

    Output:

   Is https://www.example.com a valid URL? true
Is ftp://ftp.example.com a valid URL? true
Is invalid-url a valid URL? false

By following these steps, you can easily check if a string is a valid URL in Kotlin.