Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 71 ยท State and Data

Forms and Validation

Build React Native forms with controlled inputs, React Hook Form and Zod validation, keyboard flow with refs and returnKeyType, and clear error messages.

Sign-up screens, login screens, checkout screens, note editors: forms are where users give your app their data, and where they most often get stuck. A good mobile form does four things. It keeps the typed values in state, it checks them with clear rules, it shows errors in helpful places at helpful times, and it makes the keyboard work for the user instead of against them.

You already know the building block, the controlled TextInput, from Text and TextInput. This lesson builds on it: first by hand, then with React Hook Form and Zod, the most popular pair for forms in React Native, and finally the keyboard details that separate a pleasant form from a frustrating one.

What runs on this site. TextInput, React Hook Form and Zod are installed in a real app, so their code is read-only here. The runnable examples are stand-ins rendered to HTML: a tiny schema validator shaped like Zod, and a form with the same behaviour you would build (touched-based errors, Enter moving to the next field, submit that focuses the first mistake).

A form by hand

With plain state, each field has a value and the form has a submit function that checks them all:

JSX
import { useState } from 'react';
import { View, Text, TextInput, Button } from 'react-native';

export function LoginForm({ onSubmit }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [errors, setErrors] = useState({});

  function submit() {
    const next = {};
    if (!/^\S+@\S+\.\S+$/.test(email)) next.email = 'Enter a valid email';
    if (password.length < 8) next.password = 'At least 8 characters';
    setErrors(next);
    if (Object.keys(next).length === 0) onSubmit({ email, password });
  }

  return (
    <View>
      <TextInput value={email} onChangeText={setEmail} placeholder="Email" keyboardType="email-address" autoCapitalize="none" />
      {errors.email && <Text>{errors.email}</Text>}
      <TextInput value={password} onChangeText={setPassword} placeholder="Password" secureTextEntry />
      {errors.password && <Text>{errors.password}</Text>}
      <Button title="Sign in" onPress={submit} />
    </View>
  );
}

This is fine for two fields. With ten fields, rules for each, "touched" tracking and a confirm-password check, the code balloons. That is when a form library pays off.

When to show an error

On submit Simple, but the user learns late.
After leaving the field Called "touched". Usually the best balance.
While typing Only after the first error, or it nags.

Never show errors on a field the user has not touched yet.

1 / 2

Describing rules with Zod

Zod lets you describe the shape of valid data as a schema. Parsing data against the schema either returns clean, typed data or a list of problems with their messages. Because the schema is separate from the screen, you can reuse it for the API client or the server.

JSX
import { z } from 'zod';

const signUpSchema = z
  .object({
    email: z.string().min(1, 'Email is required').email('Enter a valid email'),
    password: z.string().min(8, 'At least 8 characters'),
    confirm: z.string(),
  })
  .refine((data) => data.password === data.confirm, {
    message: 'Passwords do not match',
    path: ['confirm'],
  });

// In TypeScript, the type comes for free:
// type SignUpValues = z.infer<typeof signUpSchema>;

The .refine part checks a rule that involves two fields and attaches the message to the confirm field with path. Newer Zod versions also offer shorter helpers such as z.email(); the idea is identical, so use whichever your installed version documents.

To see how such a validator works inside, here is a stand-in with the same shape. It is not Zod (which is far more capable); it is about forty lines that return either data or a message per field, so you can watch the rules fire.

A tiny schema validator, shaped like Zod

React Hook Form

React Hook Form (RHF) tracks values, errors and touched state for you and calls a submit handler only when everything is valid. On the web it can attach to ordinary inputs, but React Native inputs are controlled components, so you connect each one with RHF's Controller. Plug in the schema with a resolver:

JSX
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { View, Text, TextInput, Button, ScrollView } from 'react-native';

export function SignUpForm({ onSignUp }) {
  const {
    control,
    handleSubmit,
    setError,
    formState: { isSubmitting },
  } = useForm({
    resolver: zodResolver(signUpSchema),
    defaultValues: { email: '', password: '', confirm: '' },
    mode: 'onTouched', // validate when a field is left, then on every change
  });

  const submit = async (values) => {
    try {
      await onSignUp(values);
    } catch (error) {
      // Show a server-side problem on the matching field
      setError('email', { message: 'That email is already registered' });
    }
  };

  return (
    <ScrollView keyboardShouldPersistTaps="handled">
      <Controller
        control={control}
        name="email"
        render={({ field: { onChange, onBlur, value, ref }, fieldState: { error } }) => (
          <View>
            <TextInput
              ref={ref}
              value={value}
              onChangeText={onChange}
              onBlur={onBlur}
              placeholder="Email"
              keyboardType="email-address"
              autoCapitalize="none"
              autoComplete="email"
            />
            {error && <Text accessibilityRole="alert">{error.message}</Text>}
          </View>
        )}
      />
      {/* password and confirm fields are written the same way */}
      <Button title={isSubmitting ? 'Creating...' : 'Create account'} onPress={handleSubmit(submit)} disabled={isSubmitting} />
    </ScrollView>
  );
}

A few points about this code. mode: 'onTouched' gives the "show the error after leaving the field" behaviour. Passing ref to the input lets RHF focus the first invalid field on a failed submit. handleSubmit(submit) runs validation and calls submit only if the data is valid. And setError is how you show a server-side error such as "email already taken": the client can only check shape, never whether an address is free. Always validate again on the server, because client checks are a courtesy, not security.

Keyboard flow

Typing on a phone is slow, so a form should let the user move through it with the keyboard's action key, without reaching to tap each field. Three props do the work:

  • returnKeyType sets the label of the action key: "next" for all fields except the last, "done" (or "go", "send") for the last.
  • onSubmitEditing runs when that key is pressed. Use it to focus the next input through a ref.
  • submitBehavior="submit" keeps the keyboard open after the key press. Without it, a single-line input dismisses the keyboard, which is annoying when moving to another field. (Older code used blurOnSubmit={false} for this.)
JSX
const passwordRef = useRef(null);
const confirmRef = useRef(null);

<TextInput
  placeholder="Email"
  returnKeyType="next"
  submitBehavior="submit"
  onSubmitEditing={() => passwordRef.current?.focus()}
/>
<TextInput
  ref={passwordRef}
  placeholder="Password"
  secureTextEntry
  returnKeyType="next"
  submitBehavior="submit"
  onSubmitEditing={() => confirmRef.current?.focus()}
/>
<TextInput
  ref={confirmRef}
  placeholder="Confirm password"
  secureTextEntry
  returnKeyType="done"
  onSubmitEditing={handleSubmit(submit)}
/>

Also set the content hints so the system can help: keyboardType ("email-address", "phone-pad", "numeric"), autoCapitalize="none" for emails and usernames, autoComplete and textContentType so password managers can fill the fields, and secureTextEntry for passwords. Wrap long forms in a ScrollView with keyboardShouldPersistTaps="handled" so a tap on the submit button works while the keyboard is open (see ScrollView and Keyboard Handling).

Putting it together: a validated form

This stand-in form follows every rule above. Errors appear only after you leave a field (touched) or press submit. Pressing Enter moves to the next field, like returnKeyType="next" with a ref; Enter in the last field submits. A failed submit focuses the first field with an error. A successful submit prints the data, never sending it anywhere.

Touched errors, Enter-to-next and focus on submit

Try pressing submit on the empty form: all three messages appear and the cursor jumps to Email. Type a valid email, press Enter, and notice no error showed up on the password field you have not touched yet.

Practical advice

  • Do not disable the submit button silently. A greyed-out button does not tell the user why. Leave it enabled and show what is wrong, or disable it only while submitting.
  • Trim and normalize input (email.trim().toLowerCase()) before validating and sending.
  • Prevent double submits. Disable the button while a request is in flight.
  • Keep the keyboard out of the way. Make sure the focused field stays visible; the next lessons cover keyboard avoidance and common pitfalls.
  • Mark errors for screen readers with accessibilityRole="alert" (and on Android a live region), as described in Accessibility in React Native.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do React Native forms with React Hook Form use the Controller component?

    RHF cannot attach to native inputs like it can to DOM inputs, so Controller connects value, onChange, onBlur and ref explicitly.
  2. 2. Which mode gives you errors after the user leaves a field and then keeps them updated as they type?

    onTouched validates on blur first, then on every change, which avoids nagging someone who has not finished typing.
  3. 3. What do returnKeyType="next" and onSubmitEditing do together?

    returnKeyType changes the key's label; onSubmitEditing runs when it is pressed, and calling focus() on the next input's ref completes the flow.
  4. 4. Why must a server validate the data again even when the app already validated it?

    Client validation is for user experience. Anyone can send requests without your app, so the server has to enforce the rules.

Summary

  • A form is controlled state, rules, well-timed errors and good keyboard behaviour.
  • Zod describes valid data as a schema (with .refine for rules across fields); React Hook Form tracks values and errors and works with React Native through Controller and a resolver.
  • mode: 'onTouched' shows errors after a field is left; use setError for server-side problems and always validate on the server too.
  • Keyboard flow: returnKeyType, onSubmitEditing with refs, submitBehavior="submit", plus keyboardType, autoCapitalize and autoComplete hints.
  • Show specific errors beside the field, announce them to screen readers, trim input and prevent double submits.
  • On this site the real libraries are read-only; the validator and form are stand-ins that behave the same way.

Continue with device capabilities in Camera, Location and Sensors.