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 numeric which almost gets me there for input except for the period (.). However this does nothing to stop pasting non-numeric characters into the field.
What I've come up with so far is to use the OnChangeText event to look at the text entered. I remove any non-numeric characters from the text. Then put the text in a state field. Then update the TextInput through it's Value property. Code snippet below.
<TextInput
style={styles.textInput}
keyboardType = 'numeric'
onChangeText = {(text)=> this.onChanged(text)}
value = {this.state.myNumber}
/>
onTextChanged(text) {
// code to remove non-numeric characters from text
this.setState({myNumber: text})
}
This seems to work but it seems like a hack. Is there another way to do this?
keyboardType='numeric'prop in TextInput to only show Numeric Keyboard (duh) and also replacing texts with regextext.replace(/[^0-9]/g, '')as suggested below to prevent anyone from pasting strings inside the TextInput. Is working fine so far on React Native v0.62