Validation on Edit Text

2019-01-24 13:45发布

问题:

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.

回答1:

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



回答2:

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


回答3:

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/



回答4:

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