DEV Community

skptricks
skptricks

Posted on • Originally published at skptricks.com on

React Native TextInput that only accepts numeric characters


source : React Native TextInput That Only Accepts Numeric Characters

This tutorial explains How to Get Only Numeric Value From TextInput in React Native application. By default TextInput component will not display numeric text qwerty keyboard. By default both Android and iOS applications open the normal multi purpose keyboard with Alphabetic Keys, Numeric Keys and Special Symbol Keys. But when developer needs to exclusively get phone number or any other numeric value from user then this is must that only Numeric Keyboard opens on TextInput selection, So that user cannot enter alphabetic value by mistake.

React Native TextInput that only accepts numeric characters

In this example we are going to create TextInput component, which will accept only numeric characters via Numeric Number Keyboard. For that we need to explicitly specify the keyboardType={‘numeric’} prop in TextInput Component.

Lets see the below complete source code that helps to display numeric value in android or ios qwerty keyboard.

/\*\*  
 \* Sample React Native App  
 \* https://github.com/facebook/react-native  
 \* @flow  
 \*/  

import React, { Component } from "react";  
import { Platform, StyleSheet, View, Button, TextInput, } from "react-native";  

export default class App extends Component {  

  render() {  
return (  
<View style={styles.container}>  

<TextInput  
          placeholder="Enter Your Mobile Number"  
          underlineColorAndroid='transparent'  
          style={styles.TextInputStyle}  
**keyboardType={'numeric'}**  
/>  

</View>  
);  
}  
}  

const styles = StyleSheet.create({  
  container: {  
    flex: 1,  
    justifyContent: 'center',  
},  
  headerText: {  
    fontSize: 20,  
    textAlign: "center",  
    margin: 10,  
    fontWeight: "bold"  
},  
TextInputStyle: {  
    textAlign: 'center',  
    height: 40,  
    borderRadius: 10,  
    borderWidth: 2,  
    borderColor: '#009688',  
    marginBottom: 10  
}  
});

Screenshot :

React Native TextInput that only accepts numeric characters
This is all about React Native TextInput that only accepts numeric characters. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

Top comments (3)

Collapse
 
oscarteg profile image
Oscar te Giffel

This just makes sure that the input keyboard is numeric not that you can only input numeric characters. If someone copy and pastes in some string characters it is still valid. Also the inputs are still just a string and not an actual numeric.

Collapse
 
ajaykumar1090 profile image
Ajay Kumar Prasad

But user can't type special character. how can we implement it.

Collapse
 
zeealik profile image
Zeeshan Ali Khan

You can still type text in this box. Validation is required.