title: "react hook for form validation"
date: 2022-01-16 00:00:00
category: snippet
tags: technical
description: "yup, you guessed it"
at the time of this writing, my job has me building a multi-step form in react. there are some business requirements and technical restrictions around certain functionalities for this form that i won't rehash here, but here are the basics:
24 different steps, not necessarily linear. existing react-based design system for form components but not using react-hook-form. how to validate all of these various steps? yup to the rescue, in a few quick steps.
first, build your form and a yup schema object for that form
we're going to pass that schema to a react hook that provides consistent validation and surfaces errors. here's what that looks like:
const useValidation = () => {
}
with the react hook created, we can update our form component to use it. we pass the schema object we created and a successCallback, a function that runs if the validation passes, to the hook. we can use deconstruct the objects off of the response returned from the hook and use them in our component.
This pattern can be followed for every additional step of the form, handling validation and surfacing errors neatly with the react hook in a consistent way
title: "react hook for form validation" date: 2022-01-16 00:00:00 category: snippet tags: technical description: "yup, you guessed it"
at the time of this writing, my job has me building a multi-step form in react. there are some business requirements and technical restrictions around certain functionalities for this form that i won't rehash here, but here are the basics:
24 different steps, not necessarily linear. existing react-based design system for form components but not using react-hook-form. how to validate all of these various steps? yup to the rescue, in a few quick steps.
first, build your form and a yup schema object for that form
we're going to pass that schema to a react hook that provides consistent validation and surfaces errors. here's what that looks like:
with the react hook created, we can update our form component to use it. we pass the schema object we created and a successCallback, a function that runs if the validation passes, to the hook. we can use deconstruct the objects off of the response returned from the hook and use them in our component.
This pattern can be followed for every additional step of the form, handling validation and surfacing errors neatly with the react hook in a consistent way