Android: need to validate an edittext for non-blank input

14,773

Solution 1

You can simply check that yourField.text() is not equivalent to null or "" at the point of submission. If it is, prompt the user to input something.

Solution 2

Carefull with something though. If you have a submit button, for instance, and your user presses submit without changing the focus out of your TextEdit, your method won't be called.

Take an Activity with 2 EditTexts and 1 button named "Go":

1) User writes something in EditText1

2) User clicks on EditText2

3) Instead of writting something there just clicks go.

Your onFocusChanged() method won't be called because focus is not "lost".

If you have a validation in your Go button_click method, it will trigger, of course, but you won't achieve your goal "I was looking/hoping for was a way to give instant feedback"

You can try using TextWatcher.

Share:
14,773
Anne Gunn
Author by

Anne Gunn

Programmer / College Instructor Current: Computer Science Instructor at NWCCD / Sheridan College Previous: Founder of a small software startup building phone apps, web apps, and ebooks. Co-founder of a successful bootstrapped software startup. SOreadytohelp

Updated on June 05, 2022

Comments

  • Anne Gunn
    Anne Gunn about 2 years

    If I want to enforce a maximum length of input in an EditText field, I can use the maxLength attribute. But if I want to enforce a minimum length (in my case, simply non-blank), I find no corresponding minLength attribute.

    I've also looked at the various 'inputType' attributes (phone, password, etc) but I don't see anything like 'required' or 'non-blank'.

    I can't believe this would require a custom input filter; it's more likely the answer is so obvious it just doesn't get written down in the form I'm asking the question.