0

In my React Native app I'm using the <Input> component from Native Base which is based on the standard <TextInput> component. I want to enforce a max length of 5 digits regardless of whether there's a decimal point. So if the user just types 1's, the max would be 11111, or 111.11. The problem is that since the input is a string, it considers the decimal point a character, so it stops me after 111.1.

How can I achieve this?

gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • You could remove the maxLength prop and check the string value yourself in ```onChangeText``` and then update the TextInput value accordingly, perhaps something like https://stackoverflow.com/a/61332316/4340854 – Thijs Apr 28 '22 at 15:53

1 Answers1

0

You could create a function that transforms your number into a string, remove the point and measure the length, then call this function from your onChangeText:

let nrs = [11111, 1111.1, 111.11, 111111, 111.111]

function checkIfLessThenFiveDigits (nr){
 let str = nr.toString() // e.g. "11111", "111.11", "111111"
 let woPoint = str.replace('.', '') // e.g. "11111", "11111", "111111"
 let isValid = woPoint.length <= 5

 return isValid
}

for (var i of nrs)
 console.log(i + ' is ' + checkIfLessThenFiveDigits(i))

// onChangeText={checkIfLessThenFiveDigits}
MockCher
  • 109
  • 4