Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

React Forms with Zod Validation

NotificationsYou must be signed in to change notification settings

robinweser/react-controlled-form

Repository files navigation

A package for creating controlled forms in React with baked inzod validation.
You own and control the rendered markup and the hook takes care of the state and validation.

npm versionnpm downloadsBundlephobia

Installation

# npmnpm i --save react-controlled-form# yarnyarn add react-controlled-form# pnpmpnpm add react-controlled-form

The Gist

import*asReactfrom'react'import{useForm,FieldProps}from'react-controlled-form'import{z,ZodError}from'zod'// create our schema with validation includedconstZ_RegisterInput=z.object({name:z.string().optional(),email:z.string().email(),// we can also pass custom messages as a second parameterpassword:z.string().min(8,{message:'Your password next to have at least 8 characters.'}),})typeT_RegisterInput=z.infer<typeofZ_RegisterInput>functionForm(){// we create a form by passing the schemaconst{ useField, handleSubmit, formProps, reset}=useForm(Z_RegisterInput)// now we can create our fields for each property// the field controls the state and validation per propertyconstname=useField('name')constemail=useField('email')constpassword=useField('password')functiononSuccess(data:T_RegisterInput){// do something with the safely parsed dataconsole.log(data)// reset the form to its initial statereset()}functiononFailure(error:ZodError){console.error(error)}return(<form{...formProps}onSubmit={handleSubmit(onSuccess,onFailure)}><labelhtmlFor="name">Full Name</label><inputid="name"{...name.inputProps}/><labelhtmlFor="email">E-Mail</label><inputid="email"type="email"{...email.inputProps}/><pstyle={{color:'red'}}>{email.errorMessage}</p><labelhtmlFor="password">Password</label><inputid="password"type="password"{...password.inputProps}/><pstyle={{color:'red'}}>{password.errorMessage}</p><buttontype="submit">Login</button></form>)}

Note: This is, of course, a simplified version and you most likely render custom components to handle labelling, error messages and validation styling.
For such cases, each field also exposes aprops property that extends theinputProps with non-standard HTML attributes.

API Reference

useForm

The core API that connects the form with a zod schema and returns a set of helpers to manage the state and render the actual markup.

Parameter TypeDefault Description
schemaZodObject A valid zod object schema
formatErrorMessage (error: ZodIssue, name: string) => string(error) => error.messageA custom formatter that receives the raw zod issue
import{z}from'zod'constZ_Input=z.object({name:z.string().optional(),email:z.string().email(),// we can also pass custom messages as a second parameterpassword:z.string().min(8,{message:'Your password next to have at least 8 characters.'}),})typeT_Input=z.infer<typeofZ_Input>// usage inside react componentsconst{ useField, handleSubmit, reset, formProps}=useForm(Z_Input)

formatErrorMessage

The preferred way to handle custom error messages would be to add them to the schema directly.
In some cases e.g. when receiving the schema from an API or when having to localise the error, we can leverage this helper.

import{ZodIssue}from'zod'// Note: the type is ZodIssue and not ZodError since we always only show the first errorfunctionformatErrorMessage(error:ZodIssue,name:string){switch(error.code){case'too_small':return`This field${name} requires at least${error.minimum} characters.`default:returnerror.message}}

useField

A hook that manages the field state and returns the relevant HTML attributes to render our inputs.
Also returns a set of helpers to manually update and reset the field.

Parameter TypeDefault Description
namekeyof z.infer<typeof schema>The name of the schema property that this field connects to
configConfigSeeConfigInitial field data and additional config options

Config

PropertyTypeDefault Description
valueany''Initial value
disabledbooleanfalseInitial disabled state
touchedbooleanfalseInitial touched state that indicates whether validation errors are shown or not
showValidationOn"change" |"blur" |"submit""submit"Which event is used to trigger the touched state
parseValue(Event) => any(e) => e.target.valueHow the value is received from the input element.
Usee.target.checked when working with<input type="checkbox" />
const{ inputProps, props, errorMessage, update, reset}=useField('email')

inputProps

Pass these to native HTMLinput,select andtextarea elements.
Usedata-valid to style the element based on the validation state.

typeInputProps={name:stringvalue:anydisabled:boolean'data-valid':booleanonChange:React.ChangeEventHandler<HTMLElement>onBlur?:React.KeyboardEventHandler<HTMLElement>}

props

Pass these to custom components that render label and input elements.
Also includes information such aserrorMessage orvalid that's non standard HTML attributes and thus can't be passed to native HTMLinput elements directly.

typeProps={value:anyname:stringvalid:booleanrequired:booleandisabled:booleanerrorMessage?:stringonChange:React.ChangeEventHandler<HTMLElement>onBlur?:React.KeyboardEventHandler<HTMLElement>}

errorMessage

Note: If you're usingprops, you already get the errorMessage!

A string containing the validation message. Only returned if the field is invalidand touched.

update

Programmatically change the data of a field. Useful e.g. when receiving data from an API.
If value is changed, it will automatically trigger re-validation.

Note: If you know the initial data upfront, prefer to pass it to theuseField hook directly though.

update({value:'Foo',touched:true,})

reset

Resets the field back to its initial field data.

reset()

handleSubmit

Helper that wraps the nativeonSubmit event on<form> elements.
It prevents default action execution and parses the form data using the zod schema.

Parameter Type Description
onSuccess(data: z.infer<typeof schema>)Callback on successful safe parse of the form data
onFailure(error: ZodError)Callback on failed safe parse
import{ZodError}from'zod'functiononSuccess(data:T_Input){console.log(data)}functiononFailure(error:ZodError){console.error(error)}// <form> onSubmit handlerconstonSubmit=handleSubmit(onSuccess,onFailure)

reset

Resets the form fields back to their initial field data. Helpful when trying to clear a form after a successful submit.

Note: This API is similar to thereset helper that theuseField hook returns. The only difference is that it resets all fields.

reset()

isDirty

Returns whether the form is dirty, meaning that any of the fields was altered compared to their initial state.
Useful e.g. when conditionally showing a save button or when you want to inform a user that he's closing a modal with unsafed changes.

isDirty()

formProps

An object that contains props that are passed to the native<form> element.Currently only consists of a single prop:

constformProps={noValidate:true,}

Recipes

Non-String Values

By default,useField expects string values and defaults to an empty string if no initial value is provided.
In order to also support e.g.boolean values or arrays, we can customise the types and pass new values.

import{ChangeEvent}from'react'constacceptsTerms=useField<boolean,ChangeEvent<HTMLInputElement>>('terms',{// alter how the value is obtained if neccessary// e.g. for checkboxes or custom inputsparseValue:(e)=>e.target.checked,// set an initial value overwritting the default empty stringvalue:false,})// custom multi-select input that returns an array of values on changetypeTags=Array<string>typeTagsChangeEvent=(value:Tags)=>voidconsttags=useField<Tags,TagsChangeEvent>('tags',{parseValue:(value)=>value,value:[],})

Passing a custom value type and change event will also change the type offield.value and the expected input forupdate.

License

react-controlled-form is licensed under theMIT License.
Documentation is licensed underCreative Common License.
Created with ♥ by@robinweser and all the great contributors.

About

React Forms with Zod Validation

Topics

Resources

Stars

Watchers

Forks

Contributors5


[8]ページ先頭

©2009-2025 Movatter.jp