How do you achieve a keyboard that only allows num...
# compose
s
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
I don’t think there is a way I just filter out the special characters
s
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
Ha didn’t know about toIntOrNull I was manually replacing the characters 😅
a
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
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
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
129 Views