If your app interacts with an API, it's crucial to validate inputs before making any requests. Imagine a sign-up form with fields for email and password. If the user types "HelloWorld" in the email field, that's clearly not an email.
While your API might catch it and return an error like "The email must be valid," it's more efficient to validate on both the frontend and backend. This saves time by catching errors before making unnecessary requests. So, let's dive into how to set up validation using Zod and React Hook Form.
#Step 1: Install Zod and React Hook Form
First, install the necessary packages:
#Step 2: Define a validation schema with Zod
Now, we'll create a schema to define our form's structure and validation rules:
Here, we're saying the email
must be a string and a valid email format, and password
must be a string between 3 and
20 characters.
#Step 3: Set up the form component
Let's create a basic form with fields for email and password:
#Step 4: Add React Hook Form
Now we'll integrate useForm
from React Hook Form:
We've added useForm
to handle form validation using zodResolver
to connect our Zod schema.
#Step 5: Display validation errors
Next, we'll show error messages below the inputs if validation fails. For example, if someone enters "HelloWorld" as their email, it'll trigger an error:
Now, when there's an error in either the email or password field, the relevant error message will display.
#Step 6: Handling form submission
Finally, we handle form submission with validation. When the form passes all checks, the onSubmit
function will
execute:
#Full example
Here's the complete code for reference:
#Conclusion
That's it! With Zod and React Hook Form, you can easily set up form validation in your React applications. For more advanced features, check out their documentation. Thanks for reading!