How to Implement Form Validation in React Native ?
React Native is a JavaScript framework for cross-platform mobile app development. Expo CLI simplifies React Native development with a streamlined process and helpful tools. In this article, we’ll see how to implement form validation in react native.
Form validation ensures the validity of user input by checking against specific rules or constraints. In React Native, form validation involves validating input fields based on conditions or patterns, such as email or password requirements.
Prerequisites:
Steps to Setup and Run React Native Project
Step 1: Set Up the Development Environment
To begin, ensure Expo CLI is installed on your system. If not, run this command in your terminal to install it globally:
npm install -g expo-cli
Step 2: Create React Native Application With Expo CLI
Create a new React Native project using Expo CLI by running this command in your terminal:
expo init form-vlidation-app
Step 3: Navigate to the project directory by using this command:
cd form-vlidation-app
Example: In this example, React Native component that implements a form with name, email, and password inputs. It performs validation on the inputs and displays error messages if any validation rules are not met. The form submission is handled when the form is valid.
Step 4: Open the App.js file and write down the following code in App.js.
Javascript
import React, { useState, useEffect } from 'react' ; import { View, TextInput, TouchableOpacity, Text, StyleSheet } from 'react-native' ; const App = () => { // State variables to store form inputs, // errors, and form validity const [name, setName] = useState( '' ); const [email, setEmail] = useState( '' ); const [password, setPassword] = useState( '' ); const [errors, setErrors] = useState({}); const [isFormValid, setIsFormValid] = useState( false ); useEffect(() => { // Trigger form validation when name, // email, or password changes validateForm(); }, [name, email, password]); const validateForm = () => { let errors = {}; // Validate name field if (!name) { errors.name = 'Name is required.' ; } // Validate email field if (!email) { errors.email = 'Email is required.' ; } else if (!/\S+@\S+\.\S+/.test(email)) { errors.email = 'Email is invalid.' ; } // Validate password field if (!password) { errors.password = 'Password is required.' ; } else if (password.length < 6) { errors.password = 'Password must be at least 6 characters.' ; } // Set the errors and update form validity setErrors(errors); setIsFormValid(Object.keys(errors).length === 0); }; const handleSubmit = () => { if (isFormValid) { // Form is valid, perform the submission logic console.log( 'Form submitted successfully!' ); } else { // Form is invalid, display error messages console.log( 'Form has errors. Please correct them.' ); } }; return ( <View style={styles.container}> <TextInput style={styles.input} placeholder= "Name" value={name} onChangeText={setName} /> <TextInput style={styles.input} placeholder= "Email" value={email} onChangeText={setEmail} /> <TextInput style={styles.input} placeholder= "Password" value={password} onChangeText={setPassword} secureTextEntry /> <TouchableOpacity style={[styles.button, { opacity: isFormValid ? 1 : 0.5 }]} disabled={!isFormValid} onPress={handleSubmit} > <Text style={styles.buttonText}>Submit</Text> </TouchableOpacity> { /* Display error messages */ } {Object.values(errors).map((error, index) => ( <Text key={index} style={styles.error}> {error} </Text> ))} </View> ); }; // Styles for the components const styles = StyleSheet.create({ container: { flex: 1, padding: 16, justifyContent: 'center' , }, input: { height: 60, borderColor: '#ccc' , borderWidth: 1, marginBottom: 12, paddingHorizontal: 10, borderRadius: 8, fontSize: 16, }, button: { backgroundColor: 'green' , borderRadius: 8, paddingVertical: 10, alignItems: 'center' , marginTop: 16, marginBottom: 12, }, buttonText: { color: '#fff' , fontWeight: 'bold' , fontSize: 16, }, error: { color: 'red' , fontSize: 20, marginBottom: 12, }, }); export default App; |
Step 5: To run the react native application, open the Terminal and enter the command listed below.
npx expo start
To run on Android:
npx react-native run-android
To run on Ios:
npx react-native run-ios