Reputation: 16122
I'm using TextInput
to allow only numbers using state, it works on android but not on iOS. Here's how I'm using state to allow only numbers.
handleInputChange = (text) => {
if (/^\d+$/.test(text) || text === '') {
this.setState({
text: text
});
}
}
my render method
render = () => {
return (
<View style={{
flex: 0,
flexDirection: 'row',
alignItems: 'flex-end',
marginTop: 50
}}>
<View style={{ flex: 0, marginLeft: 10 }}>
<Text style={{ fontSize: 20}}>$</Text>
</View>
<View style={{flex: 1,}}>
<TextInput
onChangeText={this.handleInputChange}
value={this.state.text}
underlineColorAndroid='transparent'
autoCorrect={false}
spellCheck={false}
style={{ paddingLeft: 5, fontSize: 20 }} />
</View>
</View>
);
}
This only works in Android, I guess because the state has changed react doesn't update the ui.
Upvotes: 4
Views: 14610
Reputation: 1145
onChangeText={value => setuserPrimaryPhone(value.replace(/[^0-9]/g, ''))}
javascript simple method replace(/[^0-9]/g, ''))}
Upvotes: 1
Reputation: 256
While having input from user you can change the keyBoard type for that particular text input box like this i.e. numeric or alphabatic etc...
<TextInput>
//contains some code
keyboardType="Numeric"
</TextInput>
Upvotes: 0
Reputation: 1479
Worked for me:
<TextInput
...
textContentType='telephoneNumber'
dataDetectorTypes='phoneNumber'
keyboardType='phone-pad'
/>
Upvotes: 1
Reputation: 2638
React native not provided keyboardType which remove punctuation from keyboard. You need to use regular expression with replace method to remove punctuation from text and set keyboardType = 'numeric'
.
Regular Expression
/[- #*;,.<>{}[]/]/gi
Example code
onTextChanged(value) {
// code to remove non-numeric characters from text
this.setState({ number: value.replace(/[- #*;,.<>\{\}\[\]\\\/]/gi, '') });
}
Please check snack link
https://snack.expo.io/@vishal7008/1e004c
Upvotes: 2
Reputation: 31
pls try this:
keyboardType='numeric'
in the tag TextInput
textContentType='telephoneNumber'
Upvotes: 3
Reputation: 16122
As Ravi Rupareliya said this's a bug, which TextInput
doesn't update, when the state text is shorter than the current TextInput value. Seems like the bug has been fixed in react-native 0.57.RC
. For now I'm using the following fix.
handleInputChange = (text) => {
const filteredText = text.replace(/\D/gm, '');
if(filteredText !== text) {
// set state text to the current TextInput value, to trigger
// TextInput update.
this.setState({ text: text });
// buys us some time until the above setState finish execution
setTimeout(() => {
this.setState((previousState) => {
return {
...previousState,
text: previousState.text.replace(/\D/gm, '')
};
});
}, 0);
} else {
this.setState({ text: filteredText });
}
}
Upvotes: 2