How to restrict the EditText to accept only alphanumeric characters
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.
In the XML, add this:
android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "
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);
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.