https://kotlinlang.org logo
#compose
Title
# compose
s

S.

03/13/2022, 8:57 PM
How do you achieve a keyboard that only allows numeric input? no dots, dashes, only 0-9
KeyboardType.Number
still allows special characters while
android:inputType="number"
doesn't
also how much can you rely on this input restriction? what possibilities does the user have to bypass it
r

Robert Menke

03/13/2022, 9:16 PM
I don’t think there is a way I just filter out the special characters
s

S.

03/13/2022, 9:19 PM
yeah I generally use something like this in the textfield
Copy code
onValueChange = {
                input = it
                inputError = input.toIntOrNull() == null
            }
and
enabled = !inputError
on the button
r

Robert Menke

03/13/2022, 11:09 PM
Ha didn’t know about toIntOrNull I was manually replacing the characters 😅
a

Adrijan Rogan

03/14/2022, 6:09 AM
I'm using
NumberPassword
input.toIntOrNull()
will fail on larger numbers and remove leading zeroes. Instead, use
input.filter { it.isDigit() }
to allow all unicode number decimal digits. You can also allow only "standard" ASCII digits.
s

S.

03/14/2022, 6:35 AM
Depends on your use case. It fails with numbers larger than an int afaik so it does this check for you. If you need something bigger use
toLontOrInt
. Leading zeros are irrelevant for actual numbers anyways. If you want to work with phone numbers etc the filter option is the better choice ofc
a

Adrijan Rogan

03/14/2022, 6:46 AM
I'm using it for a numeric password field, so I want a string as the result, not an integer. I agree there are valid use cases for
toIntOrNull
though
50 Views