Validation on Edit Text

限于喜欢 提交于 2019-11-27 18:36:41

问题


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



来源:https://stackoverflow.com/questions/1151664/validation-on-edit-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!