React Hook Form Tutorial - Numbers, Dates, Checkboxes
/ 3 min read
In the previous post we have learned how to validate text inputs in our form.
In this post we’re going to learn:
- How to validate numbers and dates in
<input >
fields.
- How to handle checkbox inputs.
We’re going to build a hotel booking form that has these requirements:
- Number of guests: number between 1 to 5.
- Check in date: date starting from tomorrow.
- Extra services that are optional for users to choose.
Define the validation schema
We define the schema fields and validations, and also convert them to the types we want instead of just using strings.
Build the UI
Same drill with the previous tutorial, we’re going to create the UI components and handle inputs and submissions.
Notice that for the guests and check-ins, I use <input type="number" />
and <input type="date" />
, and I don’t do anything special for the checkboxes.
Now submit the form with valid number of guests and check-in date and see what happens.
We already provided the valid inputs but why did the validation fail?
One important thing we need to remember about <input />
s behave: they return strings most of the time.
The type=number
and type=date
props that we use only change the appearance of the text field.
Making dates and numbers work
In order to fix this, we can convert the string inputs to the desired types using type coercion in Zod.
Now they should work just fine.
Checkbox handlings are the opposite of numbers and dates, they just work.
Refining error messages
If you submit the form with blank fields you’ll get error messages like below.
The guest number field shows the message like what we defined.
As for the date error message we can modify by doing a minor modification in the schema.
Try it yourself
I’ve summarized everything in this tutorial into the sandbox.