Skip to content

RN Lez 21: Validazione Form

Docs: Handling Text Input

  • Validare campi con messaggi di errore
  • Pattern di gestione errori per campo
  • Costruire form completi e robusti

type ErroriForm = {
nome?: string;
email?: string;
password?: string;
};
const [errori, setErrori] = useState<ErroriForm>({});

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;
};

<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,
},
});

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 },
});

PatternCodice
Stato erroriconst [errori, setErrori] = useState({})
Validazioneif (!campo) errori.campo = 'msg'
Mostrare errore{errori.campo && <Text>{errori.campo}</Text>}
Bordo errorestyle={[base, errore && stileErrore]}
Pulire erroresetErrori(prev => ({...prev, campo: undefined}))

Crea un form di registrazione con validazione:

  1. Nome (obbligatorio)
  2. Email (obbligatoria, deve contenere @)
  3. Telefono (opzionale, se inserito almeno 10 caratteri)
  4. Password (min 8, deve contenere 1 numero)
  5. Conferma password (deve matchare)
  6. Mostra errori specifici sotto ogni campo
  7. Bottone “Registrati” abilitato solo se tutto valido