Take the 2-minute tour ×

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?

share|improve this question
Do you really need to validate the EditText input at the same time the user is typing? Why don't you just validate the EditText's once the user click on the Done button? –  Cristian May 4 '10 at 6:05
That's exactly what I want: for the text to be verified when the user clicks the Done button (by Done button I mean the "Done" button on the QWERTY InputManager...NOT the form's submit button). Except that when I hit the Done button, focus stays on the last element in the form, and my validation method is never triggered. Hope my wording is clear... –  Stefan May 4 '10 at 21:26
add comment

12 Answers

up vote 80 down vote accepted

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
  1. Of the overridden methods, you could use the afterTextChanged(Editable s) method as follows
    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! :)

share|improve this answer
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 May 18 '10 at 12:30
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 May 19 '10 at 6:57
Nikhil Patil, I just use Toast to let the user know they've done something wrong. Is there some reason why that won't be effective in your case? –  Genia S. Nov 18 '10 at 21:24
Of course, Toast is a natural way on android. But when we have considerable amount of elements on screen which need validation, toasts don't seem to be the correct choice.(IMHO,It would annoy the user) I have been experimenting with TextView.setError() (developer.android.com/reference/android/widget/… –  Nikhil Patil Nov 22 '10 at 15:01
Although there is poor support on TextWatcher, it works... kinda! –  Tivie Nov 22 '10 at 17:35
show 4 more comments

TextWatcher is a bit verbose for my taste, so I made something a bit easier to swallow:

public abstract class TextValidator implements TextWatcher {
    private final TextView textView;

    public TextValidator(TextView textView) {
        this.textView = textView;

    public abstract void validate(TextView textView, String text);

    final public void afterTextChanged(Editable s) {
        String text = textView.getText().toString();
        validate(textView, text);

    final public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* Don't care */ }

    final public void onTextChanged(CharSequence s, int start, int before, int count) { /* Don't care */ }

Just use it like this:

editText.addTextChangedListener(new TextValidator(editText) {
    @Override public void validate(TextView textView, String text) {
       /* Validation code here */
share|improve this answer
+1 This abstracted way is much much better than using it as is! :) –  Nikhil Patil Oct 30 '12 at 15:01
Once we're speaking of validation, you mean EditText, I guess? –  fremmedehenvendelser Feb 17 at 15:09
add comment

If you want nice validation popups and images when an error occurs you can use the setError method as I describe here

share|improve this answer
Great thank you –  Muhammad Hewedy Jul 7 '13 at 17:44
add comment

Validation is somewhat tedious. Maybe I can help you in a more generic manner. I have written a basic framework to validate fields in Android.

It is totally free, and you can do whatever you like with it.

Kind regards,

Marc de Kwant

share|improve this answer
add comment

I find InputFilter to be more appropriate to validate text inputs on android.

Here's a simple example: How do I use InputFilter to limit characters in an EditText in Android?

You could add a Toast to feedback the user about your restrictions. Also check the android:inputType tag out.

share|improve this answer
This is a nice solution for things that can be validate as you type (alpha numeric input), but it would not work for things that should only be validate once the user is done entering the input (email address). –  Peter Ajtai Dec 13 '11 at 1:08
How would you trigger that Toast? The filter prevents any textwatchers from reacting... Perhaps with an onKeyListener? –  rattmuff Aug 23 '12 at 18:56
I triggered that Toast with an IF condition from the filter() method (in InputFilter class). –  Moisés Sep 20 '12 at 7:09
add comment


Current, as I write, natively supported through xml attributes validation methods are:

  1. alpha
  2. alpha numeric
  3. numeric
  4. generic regexp
  5. string emptyness

You can check it out here

Hope you enjoy it :)

share|improve this answer
add comment

I needed to do intra-field validation and not inter-field validation to test that my values were unsigned floating point values in one case and signed floating point values in another. Here's what seems to work for me:


Note, you must not have any spaces inside "numberSigned|numberDecimal". For example: "numberSigned | numberDecimal" won't work. I'm not sure why.

share|improve this answer
add comment

This was nice solution from here

InputFilter filter= new InputFilter() { 
            String checkMe = String.valueOf(source.charAt(i));

            Pattern pattern = Pattern.compile("[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*");
            Matcher matcher = pattern.matcher(checkMe);
            boolean valid = matcher.matches();
                Log.d("", "invalid");
                return "";
        return null; 

edit.setFilters(new InputFilter[]{filter}); 
share|improve this answer
add comment

In order to reduce the verbosity of the validation logic I have authored a library for Android. It takes care of most of the day to day validations using Annotations and built-in rules. There are constraints such as @TextRule, @NumberRule, @Required, @Regex, @Email, @IpAddress, @Password, etc.,

You can add these annotations to your UI widget references and perform validations. It also allows you to perform validations asynchronously which is ideal for situations such as checking for unique username from a remote server.

There is a example on the project home page on how to use annotations. You can also read the associated blog post where I have written sample codes on how to write custom rules for validations.

Here is a simple example that depicts the usage of the library.

@Required(order = 1)
@Email(order = 2)
private EditText emailEditText;

@Password(order = 3)
@TextRule(order = 4, minLength = 6, message = "Enter at least 6 characters.")
private EditText passwordEditText;

@ConfirmPassword(order = 5)
private EditText confirmPasswordEditText;

@Checked(order = 6, message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;

The library is extendable, you can write your own rules by extending the Rule class.

share|improve this answer
add comment

This looks really promising and just what the doc ordered for me:

EditText Validator

    public void onClickNext(View v) {
    FormEditText[] allFields    = { etFirstname, etLastname, etAddress, etZipcode, etCity };

    boolean allValid = true;
    for (FormEditText field: allFields) {
        allValid = field.testValidity() && allValid;

    if (allValid) {
        // YAY
    } else {
        // EditText are going to appear with an exclamation mark and an explicative message.

custom validators plus these built in:

  • regexp: for custom regexp
  • numeric: for an only numeric field
  • alpha: for an alpha only field
  • alphaNumeric: guess what?
  • personName: checks if the entered text is a person first or last name.
  • personFullName: checks if the entered value is a complete full name.
  • email: checks that the field is a valid email
  • creditCard: checks that the field contains a valid credit card using Luhn Algorithm
  • phone: checks that the field contains a valid phone number
  • domainName: checks that field contains a valid domain name ( always passes the test in API Level < 8 )
  • ipAddress: checks that the field contains a valid ip address
  • webUrl: checks that the field contains a valid url ( always passes the test in API Level < 8 )
  • date: checks that the field is a valid date/datetime format ( if customFormat is set, checks with customFormat )
  • nocheck: It does not check anything except the emptyness of the field.
share|improve this answer
add comment

Please Go through My Blog post on android input validation [updated].

Which has information on,

  • What is regular expression ?
  • How to validate android edittext input ?
  • Online regular expression library
  • Online regular expression testing tool
  • Learn how to write regular expression
share|improve this answer
add comment

You can get desired behavior by listening when user hit "Done" button on keyboard, also checkout other tips about working with EditText in my post "Android form validation - the right way"

Sample code:

mTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {                    
            return true;
        return false;
share|improve this answer
add comment

Your Answer


