How to useisNaN Check in ReactJS
In this approach we are using the isNaN function to restrict input in React Native applications. When users input text, the function verifies if it is a valid number. If it fails this check, the input is disregarded, effectively preventing non-numeric entries. By employing this method, only numerical values are accepted, ultimately improving data accuracy and enhancing usability.
Example:
Javascript
import React, { useState } from "react" ; import { TextInput, View, StyleSheet, Text, } from "react-native" ; const App = () => { const [number, setNumber] = useState( "" ); const handleNumberChange = (text) => { if (!isNaN(text)) { setNumber(text); } }; return ( <View style={styles.container}> <Text style={styles.title}>w3wiki</Text> <TextInput style={styles.input} value={number} onChangeText={handleNumberChange} keyboardType= "numeric" placeholder= "Enter a number" /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center" , alignItems: "center" , backgroundColor: "#f0f0f0" , }, title: { fontSize: 24, marginBottom: 20, fontWeight: "bold" , color: "green" , }, input: { width: 250, height: 50, borderWidth: 2, borderColor: "#3498db" , borderRadius: 10, paddingVertical: 10, paddingHorizontal: 20, fontSize: 18, color: "#333" , backgroundColor: "#fff" , }, }); export default App; |
Output:
How to Get Only Numeric Values in TextInput Field in React Native ?
Text input fields play a vital role in React Native applications, facilitating user interactions. However, certain situations demand restricting input to numeric values exclusively. In this article, we will delve into two distinct approaches to achieving this desired functionality.