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