Skip to main content

Lesson 8 of 8

Practice & Quiz - Forms & Validation

Test your command of react-hook-form, Zod schema validation, controlled vs uncontrolled inputs, and accessible form patterns with a practical registration form exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Registration Form with Zod Validation

Practical Exercise - Registration Form with Zod Validation
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

// โ”€โ”€โ”€ Schema - single source of truth for types & validation โ”€โ”€โ”€
const RegisterSchema = z.object({
  username: z
    .string()
    .min(3, 'Min 3 characters')
    .max(20, 'Max 20 characters')
    .regex(/^[a-zA-Z0-9_]+$/, 'Letters, numbers, underscores only'),

  email: z.string().email('Invalid email address'),

  password: z
    .string()
    .min(8, 'Min 8 characters')
    .regex(/[A-Z]/, 'Must contain uppercase')
    .regex(/[0-9]/, 'Must contain a number'),

  confirmPassword: z.string(),

  role: z.enum(['user', 'admin', 'moderator']),
  agreeToTerms: z.literal(true, {
    errorMap: () => ({ message: 'You must accept the terms' }),
  }),
}).refine(data => data.password === data.confirmPassword, {
  message: 'Passwords do not match',
  path: ['confirmPassword'],
});

type RegisterForm = z.infer<typeof RegisterSchema>;

// โ”€โ”€โ”€ Component โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
export function RegistrationForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<RegisterForm>({
    resolver: zodResolver(RegisterSchema),
    defaultValues: { role: 'user' },
  });

  const onSubmit = async (data: RegisterForm) => {
    await new Promise(r => setTimeout(r, 1000)); // simulate API call
    console.log('Registered:', data);
    reset();
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate>
      <label htmlFor="username">Username</label>
      <input id="username" {...register('username')} aria-describedby="username-error" />
      {errors.username && <span id="username-error" role="alert">{errors.username.message}</span>}

      <label htmlFor="email">Email</label>
      <input id="email" type="email" {...register('email')} />
      {errors.email && <span role="alert">{errors.email.message}</span>}

      <label htmlFor="password">Password</label>
      <input id="password" type="password" {...register('password')} />
      {errors.password && <span role="alert">{errors.password.message}</span>}

      <label htmlFor="confirmPassword">Confirm Password</label>
      <input id="confirmPassword" type="password" {...register('confirmPassword')} />
      {errors.confirmPassword && <span role="alert">{errors.confirmPassword.message}</span>}

      <label htmlFor="role">Role</label>
      <select id="role" {...register('role')}>
        <option value="user">User</option>
        <option value="admin">Admin</option>
        <option value="moderator">Moderator</option>
      </select>

      <label>
        <input type="checkbox" {...register('agreeToTerms')} />
        I agree to terms
      </label>
      {errors.agreeToTerms && <span role="alert">{errors.agreeToTerms.message}</span>}

      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? 'Registering...' : 'Register'}
      </button>
    </form>
  );
}
// npm install react-hook-form zod @hookform/resolvers

Module Quiz

Module Quiz
Question 1 of 5

What is the key performance advantage of react-hook-form's `register` API over useState for each input?

Tip

Tip

Practice Practice Quiz Forms 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โ€ฆ

Modern React: Use Hooks instead of class lifecycle methods

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Forms 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.

Common Mistake

Warning

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

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done