- Notifications
You must be signed in to change notification settings - Fork10
robinweser/react-controlled-form
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
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.
# npmnpm i --save react-controlled-form# yarnyarn add react-controlled-form# pnpmpnpm add react-controlled-form
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 apropsproperty that extends theinputPropswith non-standard HTML attributes.
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 | Type | Default | Description |
|---|---|---|---|
| schema | ZodObject | A valid zod object schema | |
| formatErrorMessage | (error: ZodIssue, name: string) => string | (error) => error.message | A 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)
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}}
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 | Type | Default | Description |
|---|---|---|---|
| name | keyof z.infer<typeof schema> | The name of the schema property that this field connects to | |
| config | Config | SeeConfig | Initial field data and additional config options |
| Property | Type | Default | Description |
|---|---|---|---|
| value | any | '' | Initial value |
| disabled | boolean | false | Initial disabled state |
| touched | boolean | false | Initial 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.value | How the value is received from the input element. Use e.target.checked when working with<input type="checkbox" /> |
const{ inputProps, props, errorMessage, update, reset}=useField('email')
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>}
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>}
Note: If you're using
props, you already get the errorMessage!
A string containing the validation message. Only returned if the field is invalidand touched.
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 the
useFieldhook directly though.
update({value:'Foo',touched:true,})
Resets the field back to its initial field data.
reset()
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)
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 the
resethelper that theuseFieldhook returns. The only difference is that it resets all fields.
reset()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()
An object that contains props that are passed to the native<form> element.Currently only consists of a single prop:
constformProps={noValidate:true,}
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.
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
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.
Contributors5
Uh oh!
There was an error while loading.Please reload this page.