Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only selected charcters based on regex in an EditText

I want to allow users only to type certain characters based on the a regex in my android applications. How do I achieve it?

like image 315
Ragunath Jawahar Avatar asked Nov 15 '10 01:11

Ragunath Jawahar


3 Answers

Used a TextWatcher as @Matt Ball suggested.

@Override
public void afterTextChanged(Editable s) {
      String text = s.toString();
      int length = text.length();

      if(length > 0 && !Pattern.matches(PATTERN, text)) {
           s.delete(length - 1, length);
      }
}

Edit Although the TextWatcher works, it would be cleaner to use an InputFilter. Check this example.

like image 110
Ragunath Jawahar Avatar answered Nov 10 '22 15:11

Ragunath Jawahar


Try this: If the character to type matches /[a-zA-Z0-9{insert valid characters here}]/ then allow it, otherwise don't.

like image 38
Niet the Dark Absol Avatar answered Nov 10 '22 16:11

Niet the Dark Absol


You could use android:digits on the xml EditText instead of using a regex.

For your allowed chars of the regex (numbers, comma and plus symbol): android:digits="0123456789,+"

And you could use a string resource as the digits value in case you want to reuse it.

like image 2
jeprubio Avatar answered Nov 10 '22 16:11

jeprubio