Home > Net >  How to restrict user from typing special characters in Search view Android?
How to restrict user from typing special characters in Search view Android?

Time:06-08

I have to restrict users from typing Special Characters in the Search view.

I have already defined the input type as textPersonName, but the users should not be able to type any Special Characters in the first place.

When I tried to cast it to an EditText. It throws an exception, as below:

  val filter: InputFilter = object : InputFilter {
            override fun filter(
                source: CharSequence,
                start: Int,
                end: Int,
                dest: Spanned?,
                dstart: Int,
                dend: Int
            ): CharSequence? {
                for (i in start until end) {
                    if (!Character.isLetterOrDigit(source[i])) {
                        return ""
                    }
                }
                return null
            }
        }
        var etSearch = searchview_filter as EditText
        etSearch.filters = arrayOf(filter)
    

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sbi.investtap, PID: 12227
    java.lang.ClassCastException: androidx.appcompat.widget.SearchView cannot be cast to android.widget.EditText

CodePudding user response:

This may help you, you need to check your input when users typing data. You need to set your validation inside filter.

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))) {
                return "";
            }
        }
        return null;
    }
};

fetch editText from searchview like this; No need to change edittext's id, because it is default android id of Search EditText.

var etSearch = searchview_filter.findViewById(R.id.search_src_text) as EditText
etSearch.filters = arrayOf(filter)

CodePudding user response:

This is how you may achieve this in Kotlin:

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))) {
                return "";
            }
        }
        return null;
    }
};


   var etSearch = searchview_filter.findViewById(R.id.search_src_text) as EditText
        etSearch.filters = arrayOf(filter)
  • Related