views:

1826

answers:

2

I need to do form input validation on a series of EditTexts. I'm using OnFocusChangeListeners to trigger the validation after the user types into each one, but this doesn't behave as desired for the last EditText.

If I click on the "Done" button while typing into the final EditText then the InputMethod is disconnected, but technically focus is never lost on the EditText (and so validation never occurs).

What's the best solution?

Should I be monitoring when the InputMethod unbinds from each EditText rather than when focus changes? If so, how?

+7  A: 

Why don't you use TextWatcher ?

Since you have a number of EditText boxes to be validated, I think the following shall suit you :

  1. Your activity implements android.text.TextWatcher interface
  2. You add TextChanged listeners to you EditText boxes
    txt1.addTextChangedListener(this);
    txt2.addTextChangedListener(this);
    txt3.addTextChangedListener(this);
  1. Of the overridden methods, you could use the afterTextChanged(Editable s) method as follows
    @Override
    public void afterTextChanged(Editable s) {
    // validation code goes here
    }

The Editable s doesn't really help to find which EditText box's text is being changed. But you could directly check the contents of the EditText boxes like

    String txt1String = txt1.getText().toString();
    // Validate txt1String

in the same method. I hope I'm clear and if I am, it helps! :)

Nikhil Patil
That looks like exactly what I need. Hadn't heard of TextWatcher (new to the SDK/API), but I'll test it out and see if it behaves the way I think it will. Thanks for the info!
Stefan
you're welcome! :) now that you're validating it, could you share how are you going to inform the user of the validation failure? I'm currently looking for best methods for the same.
Nikhil Patil
+2  A: 

Hi,

The default capabilities for text/checkbox etc validation is poor within android. I have written some supporting classes to fix this. It contains a validator interface, an abstract inplementation,a validationresult class and 2 examples of custom implemented validations. 1 for regular expressions on text and a simple one to check if a checkbox is checked.

Here is the link to my blog containing the sources and a small bit of explaining Form validation on Android: link text

Kind regards [http://nl.linkedin.com/in/marcdekwant]

Jaavaaan