Raheel Hasan
Raheel Hasan

Reputation: 6013

React Native - how to key number pad ONLY (without punctuations)

Is there a way to key a numeric keypad without punctuations?

<TextInput keyboardType='numeric' ..... />

if I use secureTextEntry={true}, it gets the right keyboard I want, but the values are replaced with *.

so, this is what im getting:

enter image description here

This is what I want:

enter image description here

Upvotes: 21

Views: 56502

Answers (6)

Daniel Tiago Fischer
Daniel Tiago Fischer

Reputation: 53

For Android in my case I prevent set any special char with Miguel Cardenas example.

Here what I did:

const inputRef = useRef(null);
const setRefValue = v => {
      const clean = v.replace(/[^0-9]/g, '');
      inputRef.current.value = clean;
      inputRef.current.setNativeProps({ text: clean });
    }
  };

<TextInput
   ref={inputRef}
   keyboardType={numeric}
   onChangeText={setRefValue}
/>

Every time type in TextInput the constant setRefValue will clean special characters.

Upvotes: 1

Vasyl Nahuliak
Vasyl Nahuliak

Reputation: 2468

Android doesn't support keyboardType without punctuations A visual guide to the React Native TextInput keyboardType prop values

Upvotes: 1

Vishal Dhanotiya
Vishal Dhanotiya

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/numeric-keyboard

Upvotes: 3

Miguel Cardenas
Miguel Cardenas

Reputation: 1263

I had the same problem.

I could solve doing something like this:

keyboardType={Device.isAndroid ? "numeric" : "number-pad"}

and then in a method call from onChangeText doing this:

const cleanNumber = number.replace(/[^0-9]/g, "");

this.setState({
  cleanNumber
});

and it the value prop of TextInput

value={this.state.cleanNumber}

Upvotes: 19

Jithesh Kt
Jithesh Kt

Reputation: 2043

keyboardType={"number-pad"} Works on Android. Note: I am using FormInput from react-native-elements.

Upvotes: 4

Karim Varela
Karim Varela

Reputation: 7652

Did you try number-pad? both number-pad and numeric work for me on iOS.

Upvotes: 2

Related Questions