Reputation: 151
TextInput component should not accept other characters than numeric.
The real problem is that when you paste inside TextInput: 555 555 555
, instead of 555555555
, I get 555 555 5
.
Other than that, I can paste whatever I want ^*D+-/6
.
I tried regex on
function handler(e) {
const tmp = e.replace(/[^0-9]/g, '');
setValue(tmp)
}
Is there any good way I can catch paste event or something?
Code is simple:
export default function App() {
const [value, setValue] = React.useState('');
function handler(e) {
setValue(e);
}
return (
<View style={styles.container}>
<TextInput
value={value}
onChangeText={handler}
keyboardType="numeric"
maxLength={9}
/>
</View>
);
}
Upvotes: 1
Views: 501
Reputation: 749
Not sure if you can catch a paste event. One way to solve your particular issue is to use regex and enforce maxLength from your onChangeText Handler.
Example
export default function App() {
const [value, setValue] = React.useState('');
function handler(text) {
if (text.length >= value.length + 2){
// Maybe this can be captured as a paste event?
// Haven't tested it, but it's an idea.
// Since key-ins cannot increase the length of the value by
// more than 1 at a time, if text length increase by 2 or more,
// then I think it's safe to assume it's a paste event.
}
const maxLength = 9
let cleanNumber = text.replace(/[^0-9]/g, "")
if (cleanNumber.length > maxLength) {
cleanNumber = cleanNumber.substr(0, maxLength)
}
setValue(cleanNumber);
}
return (
<View style={styles.container}>
<TextInput
value={value}
onChangeText={handler}
keyboardType="numeric"
// maxLength={9} <-- Don't use maxLength prop here.
/>
</View>
);
}
Upvotes: 1