Monday, April 18, 2022

Preventing non-numeric values using Regular Expression in React Native


Sometimes we don't want any non-numeric value to be entered into our App. This can be prevented to some extent by using the Keyboard Type props of the Text Input component, but if the user copy-pastes some non-numeric values, there is nothing much we can do about it. However, using regular expressions can help prevent this error.

Here's how to use the regular expression concept in react native : 




Source code to speed things up -


import React, { useState } from "react";
import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View, TextInput } from "react-native";

export default function App() {
const [enteredValue, setEnteredValue] = useState("");

const checkEnteredValue = (inputValue) => {
setEnteredValue(inputValue.replace(/[^0-9]/g, ""));
};
return (
<View style={styles.container}>
<View style={{ justifyContent: "center", alignItems: "center" }}>
<TextInput
style={styles.inputBox}
placeholder="enter value"
keyboardType="phone-pad"
onChangeText={checkEnteredValue()}
value={enteredValue}
></TextInput>
</View>

<StatusBar style="auto" />
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
inputBox: {
width: "80%",
height: 50,
borderWidth: 5,
borderColor: "rgba(230, 191, 131,0.7)",
marginTop: 100,
fontSize: 25,
},
});

No comments:

Post a Comment

Preventing non-numeric values using Regular Expression in React Native

Sometimes we don't want any non-numeric value to be entered into our App. This can be prevented to some extent by using the Keyboard Typ...