Not a subscriber?

Join thousands of others who are building self-directed lives through creativity, grit, and digital strategy—breaking free from the 9–5.
Receive one free message a week

Android Validation with EditText

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!