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:
Import the necessary classes:
import java.net.URL
import java.net.MalformedURLExceptionCreate 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
}
}Call the
isValidUrlfunction 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")The
URLconstructor will throw aMalformedURLExceptionif the URL string is not valid. So, we catch that exception and returnfalseif it occurs.Here are a few additional examples to demonstrate the usage of the
isValidUrlfunction: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.