Search code examples
androidandroid-edittexttextwatcherandroid-input-filter

How to filter the input of EditText?


I want to filter the input of an EditText, only digits and letters are allowed, first I use TextWatcher to deal with the last input character, but when you move the cursor or you past some content to the EditText, this method failed, now I want to know is there a way to filter the illegal input and give the user a feedback.


Solution

  • Add InputFilter to your EditText & provide a Toast for user . This code snippet will help you.

     InputFilter filter = new InputFilter() {
                    public CharSequence filter(CharSequence source, int start, int end,
                            Spanned dest, int dstart, int dend) {
                        for (int i = start; i < end; i++) {
                            if (!Character.isLetterOrDigit(source.charAt(i))) { // Accept only letter & digits ; otherwise just return
                                Toast.makeText(context,"Invalid Input",Toast.LENGTH_SHORT).show();
                                return "";
                            }
                        }
                        return null;
                    }
    
                };
    
            editText.setFilters(new InputFilter[] { filter });