React Native course ยท Module 5: Forms

Project: Atlantis Registration Form

3 min read ยท

Let's combine everything into a complete registration form!

Complete Form

import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
  View,
  Text,
  TextInput,
  Switch,
  Pressable,
  ScrollView,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
  Alert,
} from 'react-native';

// Schema
const registrationSchema = z.object({
  name: z.string().min(2, 'Min. 2 characters').max(50),
  email: z.string().email('Invalid email'),
  password: z
    .string()
    .min(8, 'Min. 8 characters')
    .regex(/[A-Z]/, 'Uppercase letter required')
    .regex(/[0-9]/, 'Digit required'),
  confirmPassword: z.string(),
  birthDate: z.date().refine(
    (date) => {
      const age = (Date.now() - date.getTime()) / (365.25 * 24 * 60 * 60 * 1000);
      return age >= 18;
    },
    { message: 'You must be at least 18 years old' }
  ),
  newsletter: z.boolean(),
  terms: z.literal(true, {
    errorMap: () => ({ message: 'You must accept the terms' }),
  }),
}).refine((data) => data.password === data.confirmPassword, {
  message: 'Passwords must match',
  path: ['confirmPassword'],
});

type FormData = z.infer<typeof registrationSchema>;

export function RegistrationForm() {
  const {
    control,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<FormData>({
    resolver: zodResolver(registrationSchema),
    defaultValues: {
      name: '',
      email: '',
      password: '',
      confirmPassword: '',
      birthDate: new Date(),
      newsletter: true,
      terms: false,
    },
  });

  const onSubmit = async (data: FormData) => {
    try {
      // Simulate API call
      await new Promise((resolve) => setTimeout(resolve, 2000));

      Alert.alert(
        'Success!',
        `Welcome to Atlantis, ${data.name}!`,
        [{ text: 'OK', onPress: () => reset() }]
      );
    } catch (error) {
      Alert.alert('Error', 'Registration failed');
    }
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView contentContainerStyle={styles.scroll}>
        <Text style={styles.title}>Register in Atlantis</Text>

        {/* Name */}
        <View style={styles.field}>
          <Text style={styles.label}>Name</Text>
          <Controller
            control={control}
            name="name"
            render={({ field: { onChange, onBlur, value } }) => (
              <TextInput
                style={[styles.input, errors.name && styles.inputError]}
                placeholder="Your name"
                onBlur={onBlur}
                onChangeText={onChange}
                value={value}
              />
            )}
          />
          {errors.name && (
            <Text style={styles.error}>{errors.name.message}</Text>
          )}
        </View>

        {/* Email */}
        <View style={styles.field}>
          <Text style={styles.label}>Email</Text>
          <Controller
            control={control}
            name="email"
            render={({ field: { onChange, onBlur, value } }) => (
              <TextInput
                style={[styles.input, errors.email && styles.inputError]}
                placeholder="email@atlantis.sea"
                keyboardType="email-address"
                autoCapitalize="none"
                onBlur={onBlur}
                onChangeText={onChange}
                value={value}
              />
            )}
          />
          {errors.email && (
            <Text style={styles.error}>{errors.email.message}</Text>
          )}
        </View>

        {/* Password */}
        <View style={styles.field}>
          <Text style={styles.label}>Password</Text>
          <Controller
            control={control}
            name="password"
            render={({ field: { onChange, onBlur, value } }) => (
              <TextInput
                style={[styles.input, errors.password && styles.inputError]}
                placeholder="Min. 8 characters"
                secureTextEntry
                onBlur={onBlur}
                onChangeText={onChange}
                value={value}
              />
            )}
          />
          {errors.password && (
            <Text style={styles.error}>{errors.password.message}</Text>
          )}
        </View>

        {/* Confirm password */}
        <View style={styles.field}>
          <Text style={styles.label}>Confirm password</Text>
          <Controller
            control={control}
            name="confirmPassword"
            render={({ field: { onChange, onBlur, value } }) => (
              <TextInput
                style={[styles.input, errors.confirmPassword && styles.inputError]}
                placeholder="Repeat password"
                secureTextEntry
                onBlur={onBlur}
                onChangeText={onChange}
                value={value}
              />
            )}
          />
          {errors.confirmPassword && (
            <Text style={styles.error}>{errors.confirmPassword.message}</Text>
          )}
        </View>

        {/* Newsletter */}
        <Controller
          control={control}
          name="newsletter"
          render={({ field: { onChange, value } }) => (
            <View style={styles.switchRow}>
              <Text>Atlantis Newsletter</Text>
              <Switch value={value} onValueChange={onChange} />
            </View>
          )}
        />

        {/* Terms */}
        <Controller
          control={control}
          name="terms"
          render={({ field: { onChange, value } }) => (
            <View>
              <View style={styles.switchRow}>
                <Text>I accept the terms</Text>
                <Switch value={value} onValueChange={onChange} />
              </View>
              {errors.terms && (
                <Text style={styles.error}>{errors.terms.message}</Text>
              )}
            </View>
          )}
        />

        {/* Submit */}
        <Pressable
          style={[styles.button, isSubmitting && styles.buttonDisabled]}
          onPress={handleSubmit(onSubmit)}
          disabled={isSubmitting}
        >
          {isSubmitting ? (
            <ActivityIndicator color="#fff" />
          ) : (
            <Text style={styles.buttonText}>Register</Text>
          )}
        </Pressable>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

This project combines all the techniques we learned: TextInput, KeyboardAvoidingView, react-hook-form, Zod validation, Switch, and styling!

Code for this lesson: App.tsx
import React from 'react';
import { View, Text, TextInput, Switch, Pressable, StyleSheet } from 'react-native';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  name: z.string().min(2, 'Min. 2 characters'),
  email: z.string().email('Invalid email'),
  newsletter: z.boolean(),
});

type FormData = z.infer<typeof schema>;

export default function App() {
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<FormData>({
    // TODO: connect schema validation via resolver: zodResolver(schema)
    defaultValues: { name: '', email: '', newsletter: true },
  });

  const onSubmit = (data: FormData) => console.log(data);

  return (
    <View style={styles.container}>
      {/* TODO: add a <Controller name="name"> with a <TextInput> (onChange, onBlur, value) and placeholder "Name" */}

      {/* TODO: add a <Controller name="email"> with a <TextInput> (keyboardType="email-address") and placeholder "Email" */}

      <Controller
        control={control}
        name="newsletter"
        render={({ field: { onChange, value } }) => (
          <View style={styles.row}>
            <Text style={styles.label}>Atlantis newsletter</Text>
            {/* TODO: add a <Switch value={value} onValueChange={onChange} /> */}
          </View>
        )}
      />

      <Pressable style={styles.button} onPress={handleSubmit(onSubmit)}>
        <Text style={styles.buttonText}>Sign up</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    backgroundColor: '#1a5276',
  },
  input: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 14,
    fontSize: 16,
    color: '#1a5276',
    marginBottom: 8,
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginVertical: 12,
  },
  label: {
    color: '#fff',
    fontSize: 16,
  },
  error: {
    color: '#e74c3c',
    marginBottom: 12,
  },
  button: {
    backgroundColor: '#2980b9',
    borderRadius: 8,
    padding: 14,
    alignItems: 'center',
    marginTop: 12,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
});

Docs entries used in this lesson

Spotted a mistake in this lesson?

Hands-on tasks in the game

  • Code editor

    Complete the code combining all the learned techniques.

Useful articles