Lucky_girl
Lucky_girl

Reputation: 4883

I have a TextInput, how to enable only numbers less than 9999.99?

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
        })
}

Upvotes: 0

Views: 165

Answers (1)

bennygenel
bennygenel

Reputation: 24680

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 + ''
    });
  }

Upvotes: 2

Related Questions