开发者

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 and开发者_运维问答roid applications. How do I achieve it?


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.


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.


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


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() ?: "")
  }
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜