In React-Native project, I have an Input component from Native Base and I want to this component to take only numeric values 0-9 and give this field default value, I looked for other questions about this issue, I do not know maybe those answers are for 'textInput' component or somehow suggestions did not work for me? Can you help me please?
Asked
Active
Viewed 2.3k times
10
-
See also: https://stackoverflow.com/questions/32946793/react-native-textinput-that-only-accepts-numeric-characters – hippietrail Nov 01 '17 at 13:17
4 Answers
16

Ahmed Eid
- 4,414
- 3
- 28
- 34

Muhammad Rosyid
- 178
- 3
- 7
-
1Unfortunately that can still allow non-numeric input to get in, such as commas and dashes depending on the platform. – Eric Nov 12 '18 at 17:09
4
I grab your problem there is no attribute for Text Input to take numeric only. But I have two method for this, In first method you have to write the code for taking the value numeric this is hack but you can use it, the code is :
<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})
}

Anuj Kumar
- 160
- 1
- 2
- 11
3
keyboardType="number-pad"
see source https://facebook.github.io/react-native/docs/textinput.html#keyboardtype
2
You can use keyboardType = 'numeric'
for numeric keyboard.
<View style={styles.container}>
<Text style={styles.txtStyle}>Enter numeric value</Text>
<TextInput
placeholder={'Enter number'}
style={styles.textInputStyle}
keyboardType="numeric"
onChangeText={value => this.onChanged(value)}
value={this.state.myNumber}
/>
</View>
In first case punctuation marks are included ex:- . and -
Use regular expression to remove punctuation marks.
onChanged(value) {
this.setState({ myNumber: value.replace(/[- #*;,.<>\{\}\[\]\\\/]/gi, '') });
}
Please check snack link

Vishal Dhanotiya
- 2,512
- 1
- 13
- 32