Making an EditText field accept only letters and white spaces in Android

前端 未结 10 668
别跟我提以往
别跟我提以往 2020-12-18 21:09

I have an EditText field in my project which stands for the full name of the person.So I want only letters and spaces to be allowed in it.So I tried the following in the

相关标签:
10条回答
  • 2020-12-18 21:35

    For some reason the inclusion of "\n" can not occur at the end of the string, I searched the Google documentation, most found nothing. the only way to achieve spaces and line break is including in the middle of the string. See the example I used in one of my apps.

    android:digits="aãâáàbcçdeéfghiíjklmnoõôóòpqrstuvwxyzAÃÂÁÀBCÇDEÉFGHIÍJKLMNOÕÔÓÒPQRSTUVWXYZ1234567890@-_'+=(){}[]*%$#!?,.;\n: /?\\"
    
    0 讨论(0)
  • 2020-12-18 21:45

    Try this solution, it block entering number, special characters except space.

    editText.setFilters(new InputFilter[] {
       new InputFilter() {
       @Override
       public CharSequence filter(CharSequence cs, int start,
           int end, Spanned spanned, int dStart, int dEnd) {
    
       return cs.toString().replaceAll("[^a-zA-Z ]*","");
        }
        }
    });
    

    Kotlin Version:

    editText.filters = arrayOf(
                InputFilter { source, start, end, dest, dstart, dend ->
                    return@InputFilter source.replace(Regex("[^a-zA-Z ]*"), "")
                }
            )
    
    0 讨论(0)
  • 2020-12-18 21:50

    Add this line in your EditText tag.

    android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    Your EditText tag should look like:

    <EditText
            android:id="@+id/edt"
            android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    

    it works perfectly and no validation condition required


    update 1

    regex src.toString().matches("[a-zA-Z ]+")


    update 2

    Fair enough if that's the case then simply add space in between.

    android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    0 讨论(0)
  • 2020-12-18 21:50

    Use the following in your in your layout.xml.

    <EditText android:inputType="textPersonName" />
    
    0 讨论(0)
提交回复
热议问题