Forms and Validation

Article · 2:00

React Hook Form for the inputs, Zod for the rules, and one schema that types the data as well as checking it.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

A form built from useState per field re-renders the whole screen on every keystroke. On a phone with six fields that is noticeable. React Hook Form keeps the values in refs and only re-renders what has to change, which is why it is the standard choice on mobile rather than merely a nice one.

Zod describes the rules as a schema - this field is a string, at least eight characters, and must match that one. The reason to pair them is that a Zod schema is also a TypeScript type: z.infer<typeof schema> gives you the shape, so the form's values are typed from the same definition that validates them, and the two cannot drift apart.

Three things make a mobile form feel finished rather than merely working. Set the right keyboardType so an email field gets the @ key and a quantity gets digits. Set autoCapitalize="none" on email and password fields, because the default capitalises the first letter and users do not notice until sign-in fails. And wire returnKeyType with a ref so the keyboard's Next button moves to the following field instead of dismissing.

TS Example 1 62 lines
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { View, Text, TextInput, Pressable } from 'react-native';
import { useRef } from 'react';

// One schema. It validates AND it is the type.
const signUpSchema = z
  .object({
    email: z.string().email('That does not look like an email address'),
    password: z.string().min(8, 'At least 8 characters'),
    confirm: z.string(),
  })
  .refine((values) => values.password === values.confirm, {
    message: 'The passwords do not match',
    path: ['confirm'],
  });

type SignUpValues = z.infer<typeof signUpSchema>;

export function SignUpForm() {
  const passwordRef = useRef<TextInput>(null);

  const { control, handleSubmit, formState } = useForm<SignUpValues>({
    resolver: zodResolver(signUpSchema),
    defaultValues: { email: '', password: '', confirm: '' },
    mode: 'onBlur',
  });

  return (
    <View style={{ padding: 16, gap: 12 }}>
      <Controller
        control={control}
        name="email"
        render={({ field: { onChange, onBlur, value } }) => (
          <TextInput
            value={value}
            onChangeText={onChange}
            onBlur={onBlur}
            placeholder="Email"
            keyboardType="email-address"
            autoCapitalize="none"
            autoComplete="email"
            returnKeyType="next"
            onSubmitEditing={() => passwordRef.current?.focus()}
          />
        )}
      />
      {formState.errors.email && <Text>{formState.errors.email.message}</Text>}

      <Pressable
        disabled={formState.isSubmitting}
        onPress={handleSubmit(async (values) => {
          // values is SignUpValues - typed from the same schema.
          console.log(values.email);
        })}
      >
        <Text>Create account</Text>
      </Pressable>
    </View>
  );
}

Open this example in the editor and change it. Nothing you type is saved.