← All articles
mobile

Android Validation with EditText

Skip the validation dialog box. Android's EditText has a built-in setError method that shows an inline icon and popup message instead.

Donn Felker

Donn Felker

2011.11.23 · 1 min read · updated January 24, 2019

Here’s a quick tip to spice up your Android applications. A lot of people perform Android input validation when a button is pressed and display the validation message in a dialog as shown below.

Validation via Alert Dialog

However, there’s a much easier (and elegant way) to do this by using the built in setError construct of the EditText class in Android (note, I’m only talking about EditText in this instance). Using this method, you will get built in support for the EditText **validation control. By using the **setError method you will receive validation as shown below in the Qonqr Android app (Currently in development for release in Q1 of 2012).

Qonqr Create Account Validation Example

To get these free validation controls you simply need to perform validation on the EditText at any time during the runtime execution of your app. This could be after a button is pressed, via a Text Changed Listener or via any other method. Once you determine that your input is invalid simply call the setError method on the EditText instance as shown below.

EditText firstName = (EditText)findViewById(R.id.first_name); if( firstName.getText().toString().length() == 0 ) firstName.setError( "First name is required!" );

… and BINGO, you now have a free icon show up in the right hand side of the EditText as well as a popup validation message that shows up. As soon as the user starts typing in the EditText, the validation icon and message will disappear. 🙂 Enjoy!

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading