React Native TextInput that only accepts numeric characters
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?
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
You can do it like this. It will only accept numeric values, and limit to 10 numbers as your wish.
<TextInput
style={styles.textInput}
keyboardType='numeric'
onChangeText={(text)=> this.onChanged(text)}
value={this.state.myNumber}
maxLength={10} //setting limit of input
/>
You can see the entered value by writing the following code in your page:
{this.state.myNumber}
In the onChanged() function the code look like this:
onChanged(text){
let newText = '';
let numbers = '0123456789';
for (var i=0; i < text.length; i++) {
if(numbers.indexOf(text[i]) > -1 ) {
newText = newText + text[i];
}
else {
// your call back function
alert("please enter numbers only");
}
}
this.setState({ myNumber: newText });
}
I hope this is helpful to others.