Home > Android > Android Validation with EditText

Android Validation with EditText


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!

 

Source : http://blog.donnfelker.com/2011/11/23/android-validation-with-edittext/

Categories: Android
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: