Home > database >  How to make TextInput only accept up to 2 decimal places with a max value?
How to make TextInput only accept up to 2 decimal places with a max value?

Time:11-05

Here's my code snippet of a TextInput component in React-Native:

enter image description here

The render on the simulator looks like this:

enter image description here

I want to make the input field only accept decimal number <= 11.99 to mimic the highest input for inches for a person's height. In onChangeText function, I'm updating the value of the state. Any ideas how I can implement this input bound with a max value? Do I check the value inside onChangeText and then set the values accordingly?

CodePudding user response:

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places. this question is duplicate. try this link allow 2 decimal

CodePudding user response:

Your can check the value of the user's input in the onChangeText.

onChangeText={(value) => {
    const parsedQty = Number.parseFloat(value) // Convert input value to a Float
    if(Number.isNaN(parsedQty)){
        setFieldValue(0) // In case user input a characters instead of a number
    } else if(parsedQty >= 11.99) {
        setFiledValue(11.99) // Set the value to 11.99 if the user input more than 11.99
    } else if (parsedQty < 0) {
        setFieldValue(0) // Set the value to 0 if the user input is below 0. You can customize this part if you want a minimum value
    } else {
        setFieldValue(parsedQty)
    }
}}
  • Related