Android: How can I validate EditText input?

2019-01-01 05:08发布

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?

14条回答
宁负流年不负卿
2楼-- · 2019-01-01 05:30

In main.xml file

You can put the following attrubute to validate only alphabatics character can accept in edittext.

Do this :

  android:entries="abcdefghijklmnopqrstuvwxyz"
查看更多
梦该遗忘
3楼-- · 2019-01-01 05:32

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

Screenshot of the use of setError taken from Donn Felker, the author of the linked post

查看更多
高级女魔头
4楼-- · 2019-01-01 05:32

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:

    <EditText
        android:id="@+id/x" 
        android:background="@android:drawable/editbox_background" 
        android:gravity="right" 
        android:inputType="numberSigned|numberDecimal" 
    />

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

查看更多
浅入江南
5楼-- · 2019-01-01 05:33

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.

查看更多
只靠听说
6楼-- · 2019-01-01 05:33

I wrote a class that extends EditText which supports natively some validation methods and is actually very flexible.

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

查看更多
回忆,回不去的记忆
7楼-- · 2019-01-01 05:34

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.
查看更多
登录 后发表回答