React Native TextInput that only accepts numeric characters

前端 未结 19 1021
轮回少年
轮回少年 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:40

    Function to validate input:

    validateInputs(text, type) {
    let numreg = /^[0-9]+$/;
      if (type == 'username') {
        if (numreg.test(text)) {
          //test ok
        } else {
          //test not ok
        } 
      }
    }
    
    
    
    <TextInput
       onChangeText={text => this.validateInputs(text, 'username')}
    />
    

    I hope this is helpful.

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

    React Native TextInput provides keyboardType props with following possible values : default number-pad decimal-pad numeric email-address phone-pad

    so for your case you can use keyboardType='number-pad' for accepting only numbers. This doesn't include '.'

    so,

    <TextInput 
      style={styles.textInput}
      keyboardType = 'number-pad'
      onChangeText = {(text)=> this.onChanged(text)}
      value = {this.state.myNumber}
    />
    

    is what you have to use in your case.

    for more details please refer the official doc link for TextInput : https://facebook.github.io/react-native/docs/textinput#keyboardtype

    0 讨论(0)
  • 2020-12-02 11:41
    <TextInput autoCapitalize={'none'} maxLength={10} placeholder='Mobile Number'  value={this.state.mobile} onChangeText={(mobile) => this.onChanged(mobile)}/>
    

    and onChanged method :

    onChanged(text){
       var newText = '';
       var numbers = '0123456789';
       if(text.length < 1){
         this.setState({ mobile: '' });
       }
       for (var i=0; i < text.length; i++) {
            if(numbers.indexOf(text[i]) > -1 ) {
                 newText = newText + text[i];
            }
            this.setState({ mobile: newText });
        }
    }
    
    0 讨论(0)
  • 2020-12-02 11:42

    Using a RegExp to replace any non digit is faster than using a for loop with a whitelist, like other answers do.

    Use this for your onTextChange handler:

    onChanged (text) {
        this.setState({
            mobile: text.replace(/[^0-9]/g, ''),
        });
    }
    

    Performance test here: https://jsperf.com/removing-non-digit-characters-from-a-string

    0 讨论(0)
  • 2020-12-02 11:43
    if (!/^[0-9]+$/.test('123456askm')) {
      consol.log('Enter Only Number');
    } else {
        consol.log('Sucess');
    }
    
    0 讨论(0)
  • 2020-12-02 11:44

    This not work on IOS, setState -> render -> not change the text, but can change other. The textinput can't change itself value when textOnChange.

    by the way, This work well on Android.

    0 讨论(0)
提交回复
热议问题