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?
TextWatcher is a bit verbose for my taste, so I made something a bit easier to swallow:
Just use it like this:
I find InputFilter to be more appropriate to validate text inputs on android.
Here's a simple example: How do I use InputFilter to limit characters in an EditText in Android?
You could add a Toast to feedback the user about your restrictions. Also check the android:inputType tag out.
This was nice solution from here
Updated approach - TextInputLayout:
Google has recently launched design support library and there is one component called TextInputLayout and it supports showing an error via
setErrorEnabled(boolean)
andsetError(CharSequence)
.How to use it?
Step 1: Wrap your EditText with TextInputLayout:
Step 2: Validate input
I have created an example over my Github repository, checkout the example if you wish to!
I have created this library for android where you can validate a material design EditText inside and EditTextLayout easily like this:
then you can use it like this:
Then you can check if it is valid like this:
For more examples and customization check the repository https://github.com/TeleClinic/SmartEditText
In order to reduce the verbosity of the validation logic I have authored a library for Android. It takes care of most of the day to day validations using Annotations and built-in rules. There are constraints such as
@TextRule
,@NumberRule
,@Required
,@Regex
,@Email
,@IpAddress
,@Password
, etc.,You can add these annotations to your UI widget references and perform validations. It also allows you to perform validations asynchronously which is ideal for situations such as checking for unique username from a remote server.
There is a example on the project home page on how to use annotations. You can also read the associated blog post where I have written sample codes on how to write custom rules for validations.
Here is a simple example that depicts the usage of the library.
The library is extendable, you can write your own rules by extending the
Rule
class.