How can I make the TextField accept only integers as input and how can I limit the number of digits before decimal to 3 and after decimal to 2?
For example NNN.NN where N is the digit.
How can I make the TextField accept only integers as input and how can I limit the number of digits before decimal to 3 and after decimal to 2?
For example NNN.NN where N is the digit.
2
Answers
The first step would be to set
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
for the TextField. This will open numeric keypad when the TextField is focused.Now the problem is that TextField doesn’t do any validation by itself (unlike the EditText with
inputType="number"
). User can type any character present on the keyboard (like commas, spaces, dashes, and even multiple decimals). You need to do all this validation by yourself.Try this code:
I haven’t tested this code but I think it should work for most of the cases. It will make sure that final input doesn’t exceed the original constraints but it might lead to some unexpected behavior. For example:
For these corner cases where user changes cursor position and types stuff, you will have to decide what the correct behavior should be (like in my 1st example, you might choose to not allow decimal removal and keep the original text). You will have to add such conditions in the
getValidatedNumber
function based on your exact requirements. One workaround that I some times use here is to disable cursor position change i.e. cursor will always remain at the end and cannot be brought to arbitrary indices.As @Arpit Shukla wrote a fine function, I had an issue with starting input with a
.
and to have the function not allow.
as a first character i’ve updated the function like so:Remark i’ve used the kotlin function
character.isDigit()
instead of being reliant on the hardcoded values.I’ve added an extra check that index is not
0
so the function does not allow the first input to be a.
.I’ve also added a check that will not allow extra
.
‘s.Peace to you ✌