I want to allow some specific characters in Edittext and block all other characters. I have searched the internet and didn't found a solution. All i found out was how to block specific characters but in my case i want to allow specific characters and block all other characters. For example the characters that i want to allow in edittext are A-Z, 0-9 and a comma, dot and underscore(_) that's it. If someone can give me an example of how to do that or point me to the right link i will be very grateful. Thanks!
Asked
Active
Viewed 1,245 times
3
-
This question already has an answer in input filter section.[See this](http://stackoverflow.com/questions/3349121/how-do-i-use-inputfilter-to-limit-characters-in-an-edittext-in-android) – Manoj Perumarath Sep 15 '16 at 09:04
-
I hope your application is English-only and won’t have to deal with different localization. Restricting input to US-ASCII doesn’t always seem to be the greatest thing. – Diti Sep 15 '16 at 09:26
1 Answers
4
One way to allow only certain characters is to use a TextChangedListener
with a Pattern
final Pattern pAlpha = Pattern.compile("[0-9a-zA-Z,._]+");
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (pAlpha.matcher(yourEditText.getText()).matches()) {
// you allowed it
} else {
// you don't allow it
}
}
});

Murat Karagöz
- 35,401
- 16
- 78
- 107
-
2While others were marking my post as negative. You provided me me with the best solution! Thanks man! – Imran Hakeem Sep 15 '16 at 11:23