Form validation in React Native ensures user inputs are correct before submission, improving data quality and user experience.
Validation is usually handled using state variables and conditional rendering to display errors.
This is a basic example checking a single field when the button is pressed.
// Example 1: Basic Email Check
import React, { useState } from "react";
import { View, TextInput, Text, Button } from "react-native";
export default function App() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const validate = () => {
if (!email.includes("@")) {
setError("Invalid email address");
} else {
setError("");
}
};
return (
<View>
<TextInput
placeholder="Enter email"
value={email}
onChangeText={setEmail}
/>
{error !== "" && <Text>{error}</Text>}
<Button title="Submit" onPress={validate} />
</View>
);
}
Here we validate two fields: Email and Password. The password must be at least 6 characters long.
// Example 2: Email & Password Validation
import React, { useState } from "react";
import { View, TextInput, Text, Button } from "react-native";
export default function LoginForm() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
// Object to hold errors for multiple fields
const [errors, setErrors] = useState({});
const validateForm = () => {
let valid = true;
let tempErrors = {};
if (!email.includes("@")) {
tempErrors.email = "Email is invalid";
valid = false;
}
if (password.length < 6) {
tempErrors.password = "Password must be 6+ chars";
valid = false;
}
setErrors(tempErrors);
return valid;
};
return (
<View>
<TextInput placeholder="Email" onChangeText={setEmail} />
{errors.email && <Text style={{color:'red'}}>{errors.email}</Text>}
<TextInput
placeholder="Password"
secureTextEntry
onChangeText={setPassword}
/>
{errors.password && <Text style={{color:'red'}}>{errors.password}</Text>}
<Button title="Login" onPress={validateForm} />
</View>
);
}
This approach clears the error message immediately as the user starts typing to fix it.
// Example 3: Real-time Validation Cleansing
const handlePasswordChange = (text) => {
setPassword(text);
// If there was an error, clear it as user types
if (errors.password) {
setErrors({ ...errors, password: null });
}
};
Try the Login Form logic below. Requirements: