Home > Net >  Android: keybord should not accept non-text characters while entering input string
Android: keybord should not accept non-text characters while entering input string

Time:09-15

Android keybord should not accept non-text characters such as space, enter, return etc while entering input string.

I tried with few, as shown below -

this is for the regex.

  1. the \b is to find word boundary.
  2. the positive look ahead (?=\w) is here to avoid spaces.
onChange = {  if (it.contains(Regex("(?=\\w)"))) onInput(it) }

but in my case first character space is not accepting but in second character onwards it is accepting. I'm new this regular expression, can any one help me?

For space -> (?=\w) value for ignore then what is the value for enter and return if any one knows please post here your answer ?

Update 1:

In EditText, If I enter non-string char at very first character of the input below code is working correctly:

onChange = {  if (it.contains(Regex("[0123456789qwertzuiopasdfghjklyxcvbnm]"))) onInput(it) }

but If I enter string char at first place and 2nd char position onwards non-text character is accepting, so my question is how to apply same condtion for all characters of the input string ?

Thanks!

CodePudding user response:

Your problem is it.contains. That will return true if any subset of the string contains a matching regex. Which any single character will match, so any string with at least 1 letter will match it. You need to match beginning and end of string as well, to make sure it only finds a valid match across the entire string.

Also, your updated example would fail any non-english language, as it would match accented letters, letters with tildes, umlats, etc. Use ^\w*$ to match any number of letters or numbers taking up the entire string.

CodePudding user response:

You could use trim() function for strings in Java/Kotlin

It will remove all the whitespaces in the text

Kotlin ->

val text = binding.etText.text.toString()
        println(text)
        println(text.trim())

Output ->

2022-09-15 11:08:49.738 4997-4997/com.ashal.******* I/System.out:         Is the te xt for mat ted?
2022-09-15 11:08:49.738 4997-4997/com.ashal.******* I/System.out: Is the text formatted?
  • Related