React Native TextInput that only accepts numeric characters

前端 未结 19 1022
轮回少年
轮回少年 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条回答
  • 2020-12-02 11:28

    Only allow numbers using a regular expression

    <TextInput 
      keyboardType = 'numeric'
      onChangeText = {(e)=> this.onTextChanged(e)}
      value = {this.state.myNumber}
    /> 
    
    onTextChanged(e) {
      if (/^\d+$/.test(e.toString())) { 
        this.setState({ myNumber: e });
      }
    }
    

    You might want to have more than one validation

    
    <TextInput 
      keyboardType = 'numeric'
      onChangeText = {(e)=> this.validations(e)}
      value = {this.state.myNumber}
    /> 
    
    numbersOnly(e) {
        return /^\d+$/.test(e.toString()) ? true : false
    }
    
    notZero(e) {
        return /0/.test(parseInt(e)) ? false : true
    }
    
    validations(e) {
        return this.notZero(e) && this.numbersOnly(e)
            ? this.setState({ numColumns: parseInt(e) })
            : false
    }
    
    
    0 讨论(0)
  • 2020-12-02 11:30

    That is the correct way to do it till such a component (or attribute on the TextInput) is specifically developed.

    The web has the ‘number’ type for the input element, but that is web based and react-native does not use a web view.

    You could consider to create that input as a react component on it’s own (maybe call NumberInput): that’ll enable you to reuse it or maybe even open source it since you can create many TextInputs that has different value filters/checkers.

    The downside to immediate correction is to ensure correct feedback is given to the user as to prevent confusion as to what happened to his value

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 11:35

    Using a RegExp to replace any non digit. Take care the next code will give you the first digit he found, so if user paste a paragraph with more than one number (xx.xx) the code will give you the first number. This will help if you want something like price, not a mobile phone.

    Use this for your onTextChange handler:

    onChanged (text) {
        this.setState({
            number: text.replace(/[^(((\d)+(\.)\d)|((\d)+))]/g,'_').split("_"))[0],
        });
    }
    
    0 讨论(0)
  • 2020-12-02 11:35

    Well, this is a very simple way to validate a number different to 0.

    if (+inputNum)
    

    It will be NaN if inputNum is not a number or false if it is 0

    0 讨论(0)
  • 2020-12-02 11:38

    You can remove non numeric characters using regex

    onTextChanged (text) {
        this.setState({
            myNumber: text.replace(/\D/g, ''),
        });
    }
    
    0 讨论(0)
提交回复
热议问题