Android: How can I validate EditText input?

Stefan picture Stefan · May 4, 2010 · Viewed 321.1k times · Source

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?

Answer

Niks picture Niks · May 18, 2010

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! :)

EDIT: For a cleaner approach refer to Christopher Perry's answer below.