Allow only selected charcters based on regex in an EditText
Solution 1
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.
Solution 2
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.
Solution 3
Try this: If the character to type matches /[a-zA-Z0-9{insert valid characters here}]/ then allow it, otherwise don't.
Solution 4
You can use an InputFilter
for advanced filtering:
class CustomInputFilter : InputFilter {
private val regex = Pattern.compile("^[A-Z0-9]*$")
override fun filter(
source: CharSequence,
start: Int,
end: Int,
dest: Spanned?,
dstart: Int,
dend: Int
): CharSequence? {
val matcher = regex.matcher(source)
return if (matcher.find()) {
null
} else {
""
}
}
}
And then add it to an EditText
or TextInputEditText
like this:
textInputLayout.editText!!.filters += CustomInputFilter()
//or
editText.filters += CustomInputFilter()
Remember that if you have a TextWatcher
this will not prevent the TextWatcher
to fire, you can filter out those events checking if the previous and next text values are the same.
Something like:
//addTextChangedListener is an extension function available in core-ktx library
textInputLayout.editText!!.addTextChangedListener(afterTextChanged = { editable ->
val editTextValue = viewModel.editTextLiveData.value ?: ""
if (!editTextValue.equals(editable)) {
viewModel.updateEditTextValue(editable?.toString() ?: "")
}
})
Ragunath Jawahar
Avid Android Developer and Entrepreneur I've been working on Android since August 2010. Latest Android Application • A Photo Editor - APE is A Photo Editor, it's amazingly simple to use. Now available on Google Play! Android Open Source Projects • Android Saripaar - The SIMPLEST annotation powered rule-based UI validation library for Android. • Adapter Kit - Set of predefined adapters to make life easier. • Instant Adapter - Create your Custom Adapters almost instantly. • Simple Section Adapter - This is the SIMPLEST section adapter available for Android's ListView as on date. • Circular List Adapter - Circular List Adapter for Android's ListView. Make your list appear infinite with a single argument constructor. • Deselectable Radio Button for Android.
Updated on June 05, 2022Comments
-
Ragunath Jawahar almost 2 years
I want to allow users only to type certain characters based on the a regex in my android applications. How do I achieve it?
-
magorich over 8 yearsThis helped me a lot, thanks I just got a problem when the user deleted a character and it didn't enter the PATTERN was crashing because an out of bounds so you can use this (with some modifications for my app) if(text.length()>0) { int length = text.length(); if (!getPattern().equals("")) { if (!Pattern.matches(getPattern(),text)) { s.delete(length - 1, length); } } }
-
Shailendra Madda over 2 yearsfrom your first line: You can use an
IntentFilter
for advanced filtering: It should beInputFilter
right? -
MatPag over 2 years@ShailendraMadda Yes it was a typo. I fixed it now, thank you :)