Let's think about it this way for a second
Form validation is typically run on submit (when the submit button is pressed) or on blur (when you leave the field) — real-time (every-keystroke) validation tends to be disruptive to the UX. Render the error message conditionally below the field (error && <Text>...), and change the TextInput's border color based on the error state for better visual feedback.
Let's connect this to a real-world scenario
Validate the email field with a regex pattern (/^\S+@\S+\.\S+$/), and show a message like 'this field is required' for empty fields — adding disabled={hasErrors} logic so the Submit button is only enabled once the errors object has no errors prevents invalid data from being submitted.
Code Example
import { useState } from 'react';
import { View, TextInput, Text, TouchableOpacity, StyleSheet } from 'react-native';
export default function SignupForm() {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
const validate = () => {
if (!email.includes('@')) {
setError('မှန်ကန်တဲ့ email format ရေးပါ');
return false;
}
setError('');
return true;
};
return (
<View style={styles.form}>
<TextInput
style={[styles.input, error && styles.inputError]}
placeholder="Email"
value={email}
onChangeText={setEmail}
onBlur={validate}
/>
{error ? <Text style={styles.errorText}>{error}</Text> : null}
</View>
);
}
const styles = StyleSheet.create({
form: { padding: 16 },
input: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 12 },
inputError: { borderColor: 'red' },
errorText: { color: 'red', marginTop: 4 },
});Type an invalid email format, then leave the field, and a red border plus an error message appear.Try it in 5 minutes
Add a password field to the signup form and implement a validation rule that errors when the password is under 8 characters.
A quick word of caution
Treat client-side validation as just a UX layer — security-critical validation (remember the SQL Injection/XSS lesson from the Cybersecurity tutorial) must always be repeated server-side too.