How to restrict the EditText to accept only alphanumeric characters

AndroidValidationAndroid Edittext

Android Problem Overview


How can I restrict an EditText to accept only alphanumeric characters, with both lowercase and uppercase characters showing as uppercase in the EditText?

<EditText
    android:id="@+id/userInput"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:minLines="3" >

    <requestFocus />
</EditText>

If a user types in lowercase "abcd", the EditText should automatically show uppercase "ABCD" without needing to restrict the keyboard to uppercase.

Android Solutions


Solution 1 - Android

In the XML, add this:

 android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "

Solution 2 - Android

>How to restrict the EditText to accept only alphanumeric characters only so that whatever lower case or upper case key that the user is typing, EditText will show upper case

The InputFilter solution works well, and gives you full control to filter out input at a finer grain level than android:digits. The filter() method should return null if all characters are valid, or a CharSequence of only the valid characters if some characters are invalid. If multiple characters are copied and pasted in, and some are invalid, only the valid characters should be kept.

public static class AlphaNumericInputFilter implements InputFilter {
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {

        // Only keep characters that are alphanumeric
        StringBuilder builder = new StringBuilder();
        for (int i = start; i < end; i++) {
            char c = source.charAt(i);
            if (Character.isLetterOrDigit(c)) {
                builder.append(c);
            }
        }

        // If all characters are valid, return null, otherwise only return the filtered characters
        boolean allCharactersValid = (builder.length() == end - start);
        return allCharactersValid ? null : builder.toString();
    }
}

Also, when setting your InputFilter, you must make sure not to overwrite other InputFilters set on your EditText; these could be set in XML, like android:maxLength. You must also consider the order that the InputFilters are set, they are applied in that order. Luckily, InputFilter.AllCaps already exists, so that applied with our alphanumeric filter will keep all alphanumeric text, and convert it to uppercase.

    // Apply the filters to control the input (alphanumeric)
    ArrayList<InputFilter> curInputFilters = new ArrayList<InputFilter>(Arrays.asList(editText.getFilters()));
    curInputFilters.add(0, new AlphaNumericInputFilter());
    curInputFilters.add(1, new InputFilter.AllCaps());
    InputFilter[] newInputFilters = curInputFilters.toArray(new InputFilter[curInputFilters.size()]);
    editText.setFilters(newInputFilters);

Solution 3 - Android

If you don't want much of customization a simple trick is actually from the above one with all characters you want to add in android:digits

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

This should work to accept alphanumeric values with Caps & Small letters.

Solution 4 - Android

Use this:

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
android:inputType="textCapCharacters"

I tried using textAllCaps="true" as suggested in a comment of accepted answer to this question but it didn't work as expected.

Solution 5 - Android

You do not want to write any regular expression for this you can just add XML properties to your Edit text

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
android:inputType="textCapCharacters"

Tested Working Perfectly for PAN Card validation.

Solution 6 - Android

try This:

private void addFilterToUserName()
    {

        sign_up_display_name_et.setFilters(new InputFilter[] {
                new InputFilter() {
                    public CharSequence filter(CharSequence src, int start,
                                               int end, Spanned dst, int dstart, int dend) {
                        if(src.equals("")){ // for backspace
                            return src;
                        }
                        if(src.toString().matches("[a-zA-Z 0-9]+")){
                            return src;
                        }
                        return "";
                    }
                }
        });
    }

Solution 7 - Android

Minimalist Kotlin approach:

fun EditText.allowOnlyAlphaNumericCharacters() {
    filters = filters.plus(
        listOf(
            InputFilter { s, _, _, _, _, _->
                s.replace(Regex("[^A-Za-z0-9]"), "")
            },
            InputFilter.AllCaps()
        )
    )
}

Solution 8 - Android

For that you need to create your custom Filter and set to your EditText like this.

This will convert your alphabets to uppercase automatically.

EditText editText = (EditText)findViewById(R.id.userInput);
InputFilter myFilter = new InputFilter() {

	@Override
	public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
		try {
			Character c = source.charAt(0);
			if (Character.isLetter(c) || Character.isDigit(c)) {
				return "" + Character.toUpperCase(c);
			} else {
				return "";
			}
		} catch (Exception e) {
		}
		return null;
	}
};
editText.setFilters(new InputFilter[] { myFilter });

No additional parameters to set in xml file.

Solution 9 - Android

<EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="PromoCode"
                    android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789,_,-"
                    android:inputType="text" />

Solution 10 - Android

This works for me:

android:inputType="textVisiblePassword"

Solution 11 - Android

Programmatically, do this:

mEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
mEditText.setFilters(new InputFilter[] {
    new InputFilter() {   
        @Override  
        public CharSequence filter(CharSequence input, int start, int end, Spanned dst, int dstart, int dend) { 
            if (input.length() > 0 && !Character.isLetterOrDigit(input.charAt(0))) {  
                // if not alphanumeric, disregard the latest input
                // by returning an empty string 
                return ""; 
            }
            return null;
        }  
    }, new InputFilter.AllCaps()
});

Note that the call to setInputType is necessary so that we are sure that the input variable is always the last character given by the user.

I have tried other solutions discussed here in SO. But many of them were behaving weird in some cases such as when you have Quick Period (Tap space bar twice for period followed by space) settings on. With this setting, it deletes one character from your input text. This code solves this problem as well.

Solution 12 - Android

I tried the solution by @methodSignature but as mentioned by @Aba it is generating the repeated/weird string. So modified it.

Kotlin:

fun EditText.allowOnlyAlphaNumericCharacters() {
filters = arrayOf(
    InputFilter { src, start, end, dst, dstart, dend ->
        if (src.toString().matches(Regex("[a-zA-Z 0-9]+"))) {
            src
        } else ""
    }
)

}

Solution 13 - Android

private static final int MAX_LENGTH =13;

et_ScanLotBrCode.setFilters(new InputFilter[]{new InputFilter.AllCaps(),new InputFilter.LengthFilter(MAX_LENGTH) });

add above code into activity or fragment, using this you can manage the length of input and uppercase letter.

Solution 14 - Android

one line answer

XML Add this textAllCaps="true"

do this onCreate()

for lower case & upper case with allowing space

yourEditText.setKeyListener(DigitsKeyListener.getInstance("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 "));

for lower case with allowing space (Required answer for this question)

yourEditText.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyz1234567890 "));

for upper case with allowing space

yourEditText.setKeyListener(DigitsKeyListener.getInstance("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3472001View Question on Stackoverflow
Solution 1 - AndroidHashir SheikhView Answer on Stackoverflow
Solution 2 - AndroidSteven ByleView Answer on Stackoverflow
Solution 3 - AndroidAjeet SinghView Answer on Stackoverflow
Solution 4 - AndroidthetanujView Answer on Stackoverflow
Solution 5 - Androidsaigopi.meView Answer on Stackoverflow
Solution 6 - AndroidGal RomView Answer on Stackoverflow
Solution 7 - AndroidmethodsignatureView Answer on Stackoverflow
Solution 8 - AndroidBiraj ZalavadiaView Answer on Stackoverflow
Solution 9 - AndroidAmir Dora.View Answer on Stackoverflow
Solution 10 - AndroidxuxuView Answer on Stackoverflow
Solution 11 - Androiduser1506104View Answer on Stackoverflow
Solution 12 - AndroidIdris BohraView Answer on Stackoverflow
Solution 13 - AndroidSainathView Answer on Stackoverflow
Solution 14 - AndroidTushar NarangView Answer on Stackoverflow