How to check if the user has typed a special character in Edittext?

Asked

Viewed 871 times

0

How can I check if the user has entered any special character (*, /, +, &, etc.) other than by if(srt.contains("@") || srt.contains("!") || ... ?

Is there any more practical way?

And if he typed, what do I do to "lock" this typing?

  • Special character you refer to which are not letters and numbers or have a specific list?

2 answers

1

Similar to William’s answer, but filtering only for letters or numbers.

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;
    }
};
seuEditTxt.setFilters(new InputFilter[] { filter });

0

Try it like this:

if ("teste".indexOf("$") >= 0)   
   // Tem $  
else  
   // Não tem $ 

You can put filter too, like this:

InputFilter filter = new InputFilter()
{
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
    {
        if (source.toString().contains("@"))
            return "";
        else
            return null; // Accept original replacement.
    }    
};

editText.setFilters(new InputFilter[] { filter });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.