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
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.
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
<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 });
}
}
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
if (!/^[0-9]+$/.test('123456askm')) {
consol.log('Enter Only Number');
} else {
consol.log('Sucess');
}
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.