I would like to know how to make a validation on EditText. For example, I have one EditText that should only accept numeric values. If something other than a numeric value is typed by the user then it should show an alert message (i.e. "please use a numeric value....").
Is there a function available to find out if the entered text is particular type? If possible please include a code snippet.
Rather than make a pop-up I would integrate a hint into the EditText and I would make it so the user could only type numbers into the EditText (android:numeric, android:hint):
<EditText android:layout_height="wrap_content"
android:numeric="integer"
android:hint="@string/numberHint"
android:gravity="left"
android:id="@+id/name"
android:layout_width="wrap_content"
android:maxWidth="60dp"
android:textSize="6pt">
</EditText>
More information is available here:
http://developer.android.com/reference/android/widget/EditText.html
Another way ,
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
Please Go through My Blog post on android input validation [updated].
EDIT:
Which has information on,
- What is regular expression
- How to validate android edittext input
- Online regular expression library
- Online regular expression testing tool
- Learn how to write regular expression
If you want nice looking validation messages you can use the setError method on the EditText control as I show here: http://blog.donnfelker.com/2011/11/23/android-validation-with-edittext/
The default capabilities for text/checkbox etc validation is poor within android. I have written some supporting classes to fix this. It contains a validator interface, an abstract inplementation,a validationresult class and 2 examples of custom implemented validations.
1 for regular expressions on text and a simple one to check if a checkbox is checked.
Here is the link to my blog containing the sources and a small bit of explaining
Form validation on Android