0

I have a text input, how is possible to allow only numbers lower than 9999.99?

   <TextInput
                    autoFocus
                    style={styles.inputStyle}
                    placeholder="0.00"
                    keyboardType="numeric"
                    maxLength={9}
                    autoCapitalize="none"
                    placeholderTextColor={Colors.white}
                    underlineColorAndroid={Colors.transparent}
                    value={billAmount}
                    onChangeText={this.handleTextChange}
                    selection={{start: cursor, end: cursor}}
                  />

Here is handleTextChange function:

handleTextChange = (text) => {
    const { cursor, billAmount } = this.state
    let newText
        newText = text.replace(/[^1-9]/g, '')
        this.setState({
          billAmount: newText
        })
}
bennygenel
  • 23,896
  • 6
  • 65
  • 78
Lucky_girl
  • 4,543
  • 6
  • 42
  • 82

1 Answers1

2

Your regex expression also removes any dots (.). This will lead you loosing any floats. If you want to enable floats you need to add . to your regex.

Then all you need to do is to parse your text to float and check if it is lower that the max float.

Sample

handleTextChange = (text) => {
    const newAmount = parseFloat(text.replace(/[^1-9.]/g, ''));
    this.setState({
      billAmount: newAmount > 10000 ? '9999.99' : newAmount + ''
    });
  }
bennygenel
  • 23,896
  • 6
  • 65
  • 78