how to validate a URL / website name in EditText in Android?

前端 未结 6 1679
深忆病人
深忆病人 2020-12-02 06:33

I want to take input, a URL or just a website name like, www.google.com from EditText in Android and on user click on the Button to submit

6条回答
  •  天涯浪人
    2020-12-02 06:41

    In case, in your UnitTest, you got NullPointerException then use PatternsCompat instead of Patterns.

    fun isFullPath(potentialUrl: String): Boolean {
        return PatternsCompat.WEB_URL.matcher(potentialUrl.toLowerCase(Locale.CANADA)).matches()
    }
    

    Also, I realized that this method returns true when I pass it Photo.jpg. My expectation is false. Therefore, I propose following method instead of the above.

    fun isFullPath(potentialUrl: String): Boolean {
        try {
            URL(potentialUrl).toURI()
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }
    

提交回复
热议问题