tjheffner / heffdotdev

personal site refresh for 2022. based on swyxkit
https://heffner.dev
MIT License
0 stars 0 forks source link

react hook for form validation #51

Closed tjheffner closed 9 months ago

tjheffner commented 1 year ago

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


const schema = yup.stuff{};

const FormStepOne = () => {
<form>
  <TextInput
</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.


const schema = yup.stuff{};

const FormStepOne = () => {
<form>
  <TextInput
</form>
}

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

tjheffner commented 9 months ago

not publishing this post as i don't have access to the project anymore. i'd also recommend looking at zod over yup