Skip to main content

Lesson 8 of 9

Mini Project: Login/Signup Form with Validation

Build a complete, production-ready auth flow: Login screen with email+password, Signup screen with multi-field Zod validation, keyboard handling, accessible error states, and a password strength indicator.

50 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Login Screen

Login Screen
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { View, Text, TextInput, Pressable, ActivityIndicator, StyleSheet, KeyboardAvoidingView, Platform, ScrollView } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useState } from 'react';

const loginSchema = z.object({
  email: z.string().email('Invalid email'),
  password: z.string().min(1, 'Password is required'),
});
type LoginData = z.infer<typeof loginSchema>;

export function LoginScreen({ onLogin }: { onLogin: (email: string) => void }) {
  const [showPassword, setShowPassword] = useState(false);
  const [serverError, setServerError] = useState('');

  const { control, handleSubmit, formState: { errors, isSubmitting } } = useForm<LoginData>({
    resolver: zodResolver(loginSchema),
    mode: 'onBlur',
  });

  async function onSubmit({ email, password }: LoginData) {
    setServerError('');
    try {
      // Simulate API
      await new Promise(r => setTimeout(r, 1200));
      if (password === 'wrong') throw new Error('Invalid credentials');
      onLogin(email);
    } catch (err) {
      setServerError(err instanceof Error ? err.message : 'Login failed');
    }
  }

  return (
    <SafeAreaView style={s.screen}>
      <KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
        <ScrollView contentContainerStyle={s.scroll} keyboardShouldPersistTaps="handled">
          <Text style={s.logo}>🚀</Text>
          <Text style={s.title}>Welcome back</Text>
          <Text style={s.subtitle}>Sign in to your account</Text>

          {serverError ? (
            <View style={s.serverError} accessibilityRole="alert">
              <Text style={s.serverErrorText}>{serverError}</Text>
            </View>
          ) : null}

          {/* Email */}
          <Text style={s.label}>Email</Text>
          <Controller
            control={control}
            name="email"
            render={({ field: { value, onChange, onBlur } }) => (
              <TextInput
                value={value}
                onChangeText={onChange}
                onBlur={onBlur}
                style={[s.input, errors.email && s.inputErr]}
                placeholder="you@example.com"
                placeholderTextColor="#475569"
                keyboardType="email-address"
                autoCapitalize="none"
                autoCorrect={false}
                returnKeyType="next"
                accessibilityLabel="Email address"
                accessibilityState={{ invalid: !!errors.email }}
              />
            )}
          />
          {errors.email && <Text style={s.errText} accessibilityRole="alert">{errors.email.message}</Text>}

          {/* Password */}
          <Text style={[s.label, { marginTop: 12 }]}>Password</Text>
          <View style={s.passwordRow}>
            <Controller
              control={control}
              name="password"
              render={({ field: { value, onChange, onBlur } }) => (
                <TextInput
                  value={value}
                  onChangeText={onChange}
                  onBlur={onBlur}
                  style={[s.input, s.passwordInput, errors.password && s.inputErr]}
                  placeholder="••••••••"
                  placeholderTextColor="#475569"
                  secureTextEntry={!showPassword}
                  autoCapitalize="none"
                  returnKeyType="done"
                  onSubmitEditing={handleSubmit(onSubmit)}
                  accessibilityLabel="Password"
                  accessibilityState={{ invalid: !!errors.password }}
                />
              )}
            />
            <Pressable onPress={() => setShowPassword(v => !v)} style={s.eyeBtn} accessibilityLabel={showPassword ? 'Hide password' : 'Show password'}>
              <Text style={s.eye}>{showPassword ? '🙈' : '👁'}</Text>
            </Pressable>
          </View>
          {errors.password && <Text style={s.errText} accessibilityRole="alert">{errors.password.message}</Text>}

          <Pressable
            onPress={handleSubmit(onSubmit)}
            disabled={isSubmitting}
            style={({ pressed }) => [s.btn, isSubmitting && s.btnDisabled, pressed && { opacity: 0.85 }]}
            accessibilityRole="button"
            accessibilityLabel={isSubmitting ? 'Signing in' : 'Sign in'}
            accessibilityState={{ disabled: isSubmitting }}
          >
            {isSubmitting
              ? <ActivityIndicator color="white" />
              : <Text style={s.btnText}>Sign In</Text>}
          </Pressable>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1, backgroundColor: '#0f172a' },
  scroll: { flexGrow: 1, justifyContent: 'center', padding: 24 },
  logo: { fontSize: 48, textAlign: 'center', marginBottom: 16 },
  title: { fontSize: 28, fontWeight: '700', color: '#f1f5f9', textAlign: 'center', marginBottom: 6 },
  subtitle: { fontSize: 15, color: '#94a3b8', textAlign: 'center', marginBottom: 32 },
  serverError: { backgroundColor: '#450a0a', borderRadius: 10, padding: 12, marginBottom: 16, borderWidth: 1, borderColor: '#dc2626' },
  serverErrorText: { color: '#fca5a5', fontSize: 14, textAlign: 'center' },
  label: { fontSize: 14, fontWeight: '600', color: '#cbd5e1', marginBottom: 6 },
  input: { backgroundColor: '#1e293b', borderWidth: 1, borderColor: '#334155', borderRadius: 10, padding: 14, fontSize: 15, color: '#f1f5f9' },
  inputErr: { borderColor: '#f87171' },
  errText: { color: '#f87171', fontSize: 12, marginTop: 4, marginBottom: 4 },
  passwordRow: { position: 'relative' },
  passwordInput: { paddingRight: 48 },
  eyeBtn: { position: 'absolute', right: 14, top: 14 },
  eye: { fontSize: 18 },
  btn: { backgroundColor: '#229c6b', borderRadius: 12, padding: 16, alignItems: 'center', marginTop: 24 },
  btnDisabled: { opacity: 0.6 },
  btnText: { color: 'white', fontSize: 16, fontWeight: '700' },
});

Tip

Tip

Practice Mini Project LoginSignup Form with Validation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Full login and registration flow with Zod validation and keyboard handling

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project LoginSignup Form with Validation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project LoginSignup Form with Validation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/9 done