React Native TextInput that only accepts numeric characters

前端 未结 19 1114
轮回少年
轮回少年 2020-12-02 10:38

I need to have a React Native TextInput component that will only allow numeric characters (0 - 9) to be entered. I can set the keyboardType to

19条回答
  •  Happy的楠姐
    2020-12-02 11:32

    I wrote this function which I found to be helpful to prevent the user from being able to enter anything other than I was willing to accept. I also used keyboardType="decimal-pad" and my onChangeText={this.decimalTextChange}

      decimalTextChange = (distance) =>
    {
        let decimalRegEx = new RegExp(/^\d*\.?\d*$/)
        if (distance.length === 0 || distance === "." || distance[distance.length - 1] === "."
            && decimalRegEx.test(distance)
        ) {
            this.setState({ distance })
        } else {
            const distanceRegEx = new RegExp(/^\s*-?(\d+(\.\d{ 1, 2 })?|\.\d{ 1, 2 })\s*$/)
            if (distanceRegEx.test(distance)) this.setState({ distance })
        }
    }
    

    The first if block is error handling for the event the user deletes all of the text, or uses a decimal point as the first character, or if they attempt to put in more than one decimal place, the second if block makes sure they can type in as many numbers as they want before the decimal place, but only up to two decimal places after the point.

提交回复
热议问题