nogabemist
nogabemist

Reputation: 487

React Native how to only allow for numbers on TextInput? Numeric is just a numerical keyboard

I want to take 6 digits as input for verification but I have problem with textinput about non-numerical characters.

First of all, I did

<TextInput maxLength={6} style={styles.textInput} onChangeText={value => this.onTextChanged(value) }  value={this.state.codeInput} keyboardType='numeric' />

And I have a function to detect non-numerical characters.

onTextChanged(value) {
    // code to remove non-numeric characters from text
    this.setState({ codeInput: value.replace(/[- #*;,.<>\{\}\[\]\\\/]/gi, '') });
  }

In mobile it only opens numeric keyboard with dot character in it. Even, user press dot character. Function doesn't allow this but my problem is physical keyboard, copy-paste and opening in web browser. I can type anything in web browser. Function doesn't effect in pc web browser.

How can I block all characters except 0-9 numbers while copy-pasting, for physical keyboards and on pc web browser.

Upvotes: 0

Views: 7426

Answers (1)

limdev
limdev

Reputation: 845

Maybe you could simply use this regexp value.replace(/[^0-9]/, '')

If you want to manage the copy and past as well, use the global flag:
value.replace(/[^0-9]/g, '')

Upvotes: 3

Related Questions