Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 or when the EditText looses the focus the URL should be validated, like it is in the format "www.anyURL.com"...

How can I do this? Is there any inbuilt functionality available in android?

like image 529
Preetam Avatar asked Apr 11 '11 06:04

Preetam


People also ask

How can I check if an android URL is valid?

Use URLUtil to validate the URL as below. It will return True if URL is valid and false if URL is invalid.

What is a URL validator?

Link validation pings the destination of a URL and tests for errors. This helps avoid broken and invalid links in your published document, and is especially useful for bloggers.


1 Answers

Short answer

Use WEB_URL pattern in Patterns Class

 Patterns.WEB_URL.matcher(potentialUrl).matches() 

It will return True if URL is valid and false if URL is invalid.

Long answer

As of Android API level 8 there is a WEB_URL pattern. Quoting the source, it "match[es] most part of RFC 3987". If you target a lower API level you could simply copy the pattern from the source and include it in your application. I assume you know how to use patterns and matchers, so I'm not going into more details here.

Also the class URLUtil provides some useful methods, e.g:

  • isHttpUrl()
  • isValidUrl()

The descriptions of the methods are not very elaborate, therefore you are probably best of looking at the source and figuring out which one fits your purpose best.

As for when to trigger the validation check, there are multiple possibilities: you could use the EditText callback functions

  • onFocusChanged(), or
  • onTextChanged()

or use a TextWatcher, which I think would be better.

DON'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

like image 179
Dimi Avatar answered Sep 21 '22 00:09

Dimi