RN Lez 21: Validazione Form
Docs: Handling Text Input
Obiettivi
Section titled “Obiettivi”- Validare campi con messaggi di errore
- Pattern di gestione errori per campo
- Costruire form completi e robusti
1. Pattern: Stato errori
Section titled “1. Pattern: Stato errori”type ErroriForm = { nome?: string; email?: string; password?: string;};
const [errori, setErrori] = useState<ErroriForm>({});2. Validazione per campo
Section titled “2. Validazione per campo”const valida = (): boolean => { const nuoviErrori: ErroriForm = {};
if (!nome.trim()) { nuoviErrori.nome = 'Il nome è obbligatorio'; }
if (!email.trim()) { nuoviErrori.email = 'L\'email è obbligatoria'; } else if (!email.includes('@')) { nuoviErrori.email = 'Email non valida (manca @)'; }
if (!password) { nuoviErrori.password = 'La password è obbligatoria'; } else if (password.length < 6) { nuoviErrori.password = 'Minimo 6 caratteri'; }
setErrori(nuoviErrori); return Object.keys(nuoviErrori).length === 0;};3. Mostrare errori nell’UI
Section titled “3. Mostrare errori nell’UI”<View style={{ marginBottom: 15 }}> <TextInput style={[ styles.input, errori.email && styles.inputErrore, // bordo rosso ]} placeholder="Email" value={email} onChangeText={(text) => { setEmail(text); // Pulisci errore quando l'utente digita setErrori(prev => ({ ...prev, email: undefined })); }} keyboardType="email-address" /> {errori.email && ( <Text style={styles.erroreTesto}>⚠ {errori.email}</Text> )}</View>const styles = StyleSheet.create({ input: { borderWidth: 1, borderColor: '#ddd', padding: 12, borderRadius: 8, fontSize: 16, backgroundColor: 'white', }, inputErrore: { borderColor: '#e74c3c', borderWidth: 2, }, erroreTesto: { color: '#e74c3c', fontSize: 13, marginTop: 4, marginLeft: 4, },});4. Form completo: Login
Section titled “4. Form completo: Login”import { useState } from 'react';import { View, Text, TextInput, Button, Alert, StyleSheet } from 'react-native';
export default function LoginForm() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [errori, setErrori] = useState<{ email?: string; password?: string }>({});
const valida = (): boolean => { const e: typeof errori = {}; if (!email.trim()) e.email = 'Email obbligatoria'; else if (!email.includes('@')) e.email = 'Email non valida'; if (!password) e.password = 'Password obbligatoria'; else if (password.length < 6) e.password = 'Min 6 caratteri'; setErrori(e); return Object.keys(e).length === 0; };
const login = () => { if (valida()) { Alert.alert('✅ Successo', 'Login valido!'); } };
return ( <View style={styles.container}> <Text style={styles.titolo}>Accedi</Text>
<Text style={styles.label}>Email</Text> <TextInput style={[styles.input, errori.email && styles.inputErrore]} value={email} onChangeText={t => { setEmail(t); setErrori({}); }} keyboardType="email-address" placeholder="nome@scuola.it" /> {errori.email && <Text style={styles.errore}>{errori.email}</Text>}
<Text style={styles.label}>Password</Text> <TextInput style={[styles.input, errori.password && styles.inputErrore]} value={password} onChangeText={t => { setPassword(t); setErrori({}); }} secureTextEntry placeholder="Almeno 6 caratteri" /> {errori.password && <Text style={styles.errore}>{errori.password}</Text>}
<Button title="Accedi" onPress={login} /> </View> );}
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', padding: 30, backgroundColor: '#f5f5f5' }, titolo: { fontSize: 28, fontWeight: 'bold', marginBottom: 30, textAlign: 'center' }, label: { fontSize: 14, fontWeight: '600', marginBottom: 5, marginTop: 15 }, input: { borderWidth: 1, borderColor: '#ddd', padding: 12, borderRadius: 8, fontSize: 16, backgroundColor: 'white' }, inputErrore: { borderColor: '#e74c3c', borderWidth: 2 }, errore: { color: '#e74c3c', fontSize: 12, marginTop: 4 },});5. Tabella riassuntiva
Section titled “5. Tabella riassuntiva”| Pattern | Codice |
|---|---|
| Stato errori | const [errori, setErrori] = useState({}) |
| Validazione | if (!campo) errori.campo = 'msg' |
| Mostrare errore | {errori.campo && <Text>{errori.campo}</Text>} |
| Bordo errore | style={[base, errore && stileErrore]} |
| Pulire errore | setErrori(prev => ({...prev, campo: undefined})) |
6. Esercizio
Section titled “6. Esercizio”🎯 “Form registrazione completa”
Section titled “🎯 “Form registrazione completa””Crea un form di registrazione con validazione:
- Nome (obbligatorio)
- Email (obbligatoria, deve contenere @)
- Telefono (opzionale, se inserito almeno 10 caratteri)
- Password (min 8, deve contenere 1 numero)
- Conferma password (deve matchare)
- Mostra errori specifici sotto ogni campo
- Bottone “Registrati” abilitato solo se tutto valido