0

I am trying to create a screen which has an EditText where an url needs to be entered and a Verify button which will be highlighted when a valid url is entered.

I wanted to know what is the logic to find whether a url entered is valid or not? Should I look for .com string in the edittext or is there any other logic? and How can I get the text as and when user enters a character so that the button gets highlighted as soon as a valid url is entered.

Thanks in advance.

Eddy Freddy
  • 1,820
  • 1
  • 13
  • 18
500865
  • 6,920
  • 7
  • 44
  • 87

3 Answers3

4
  1. Url validation: Regular expression to match URLs in Java
  2. How to enable button just when user enters a valid URL:

Let's guess your EditText has the txt_url id:

EditText editText = (EditText) findViewById(R.id.txt_url);
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        // lets supouse validation method is called validUrl()
        button.setEnabled(validUrl(editable.toString()));
    }
});
Community
  • 1
  • 1
Cristian
  • 198,401
  • 62
  • 356
  • 264
1

Try this:

UrlValidator validator = new UrlValidator();
validator.validate(url);

I think validator.validate is a boolean, but I'm not sure...

With that you culd then invoke the setVisible(true/false) of the button.

Alvin Baena
  • 903
  • 1
  • 10
  • 24
  • `UrlValidator` belongs to the Apache's Commons Validator package which is not included by default in Android. – Cristian Oct 24 '11 at 18:07
  • Good to know about UrlValidator. Thanks for the response. However, Cristian's response is more complete. – 500865 Oct 24 '11 at 18:10
1

You can try to create a URL object and catch the MalformedURLException, like this:

    editText.addTextChangedListener(new TextWatcher() {  
        @Override
        public void afterTextChanged(Editable s) {
            try {
                URL url = new URL(String.valueOf(s));
                // code to show verify button here
            } catch (MalformedURLException e) {
                // show not verified here
            }
        }
    });
skynet
  • 9,898
  • 5
  • 43
  • 52
  • 1
    This also validates URL's like http://localhost/ which may not be *valid* for some apps. It is nice though... I like it. – Cristian Oct 24 '11 at 18:18