CodeBlanks Logo Icon CodeBlanks

Challenge: Form and validation

Write a react-hook-form registration form validated with Zod.

Challenge: Form and validation

In this challenge you will write a login form with react-hook-form. The useForm hook gives register and handleSubmit.

For validation you write register('email', { required: true }). Errors land in formState.errors. You capture a valid form with handleSubmit(onSubmit). To show the error to the user you print errors.email.

Practice Write the LoginForm component

Write LoginForm. Get register and handleSubmit from useForm. Inside <form onSubmit={handleSubmit((data) => console.log(data))}> place <input {...register('email', { required: true })} /> and <button type="submit">Send</button>. Export it.

Starter code

App.jsx
import { useForm } from 'react-hook-form';

// Write the LoginForm component here

Sample solution

App.jsx
import { useForm } from 'react-hook-form';

function LoginForm() {
  const { register, handleSubmit } = useForm();
  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <input {...register('email', { required: true })} />
      <button type="submit">Send</button>
    </form>
  );
}
export default LoginForm;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Where are errors collected in react-hook-form?

  • useState.errors
  • register.errors
  • formState.errors Correct answer
  • errors state

Explanation: formState.errors carries the errors.

2 Fill in the blank: make a field required

Question
<input {...register('email', { ____: true })} />
Answer
<input {...register('email', { required: true })} />

Explanation: true makes the field mandatory.

All lessons in Advanced