Comments (4)
Even if would be great to have a solution for this, like a standard API for transform/cast between react-hookk-form state and html widget state...
In this sandbox I tried to overcome this with a restructure of data flow.
The idea is to split the schema into 2 parts: formSchema
and dataSchema
.
const dataSchema = z.object({ ... }) // schema that rapresent how datasource fetched from DB looks
const formSchema = z
.object({ ... }) // validate react-hook-form state
.transform((input)=> // then cast types for dataSchema validation)
.pipe(dataSchema); // Validate against the dataSchema
dataSchema is the schema used for validating at the Datasource (DB) level.
So the validation schema has three step
- Validate react-hook-form formValues
- If pass, cast types to expected type of the Datasource layer
- Validate against the dataSchema
This is more verbose, but more declarative and easily readable
from react-hook-form.
To give better context to this issue...
Goal
Let's say the you want a form with an input the let you select a date, but you want to set a default date.
Doing that when the user open the form a date is already in place (for example the "today" date)
This does not work
const Component = () => {
const { register } = useForm({
defaultValue: {
day: new Date("2024-12-31"),
}
})
return <input type="date" {...register('day', {valueAsDate: true })} />
}
This works - use Controller API
If you instead switch from register
API to <Controller>
API you can:
- edit how reach-hook-form => set
value
to => html input element - edit how react-hook-form => get
value
from theonChange
event and set it to => react-hook-form state
const Component = () => {
const { register } = useForm({
defaultValue: {
day: new Date("2024-12-31"),
}
})
return (
<Controller
control={control}
name="day"
render={({field}) => (
<input
{...field}
type="date"
value={field.value ? field.value.toISOString().substring(0,10) : undefined}
onChange={( {target:{value}} ) => field.onChange( value === '' ? undefined : new Date(value) ) }
/>
)}
/>
)
}
Consideration
But this means that you cannot choose which api to use (register or Controller), but as soon as you need a date input you MUST use the controller api, which is less performant
Open Question
Why not exposed in the registr api a similar way to manipulate the value between react-hook-form state and html input state (DOM state) ??
Something like
<input
type="date"
{...register("day", {
// input value => react-hook-form state
getValueFromInputAs: value => value === '' ? undefined : new Date(value),
// react-hook-form-state => input value
setValueToInputAs: value => value ? value.toISOString().substring(0,10) : undefined,
})}
/>
This works - use string instead of Date
and accept a complex validation schema
Because this doesn't work ...
const schema = z.object({
day: z.date(),
});
const Component = () => {
const { register } = useForm<z.input<typeof schema>>({
defaultValue: {
day: new Date("2024-12-31"),
}
})
// ...
}
... you can switch the field type from Date
to string
like ...
const { register } = useForm<z.input<typeof schema>>({
defaultValue: {
day: "2024-12-31", // now it's a string
}
})
... but the validation schema will complain (showing Typescript errors). You can fix this by adding more complexity to the schema, with downside of coupling the schema with HTML input behavior.
const schema = z.object({
// 1. validate html input values
day: z.string().min(1, "Required field"),
}).transform(input => ({
// 2. If step 1 is valid, cast/coerce data types for the step 3
day: new Date(input.day),
}).pipe(z.object({
// 3. validate data
day: z.date(),
});
... and updating also useForm
generic types to have correct inference inside handleSubmit
type SchemaInput = z.input<typeof schema>;
type SchemaOutput = z.output<typeof schema>;
const { register, handleSubmit } = useForm<SchemaInput, any, SchemaOutput>({
defaultValue: {
day: "2024-12-31", // now it's a string
}
})
<form onSubmit={handleSubmit((formValues) => {
// here formValues has SchemaOutput types and not SchemaInput
// so "formValues.day" is of type Date, not string
}}
from react-hook-form.
Feature request
Why not exposeing in the register
api a way to manipulate the value between react-hook-form state and DOM html input state ??
This will give "parity" with the Controller API.
Something like
<input
type="date"
{...register("day", {
// input value => react-hook-form state
getValueFromInputAs: value => value === '' ? undefined : new Date(value),
// react-hook-form-state => input value
setValueToInputAs: value => value ? value.toISOString().substring(0,10) : undefined,
})}
/>
from react-hook-form.
I am having this issue as well. defaultValue
doesn't work at all with type=date
inputs.
from react-hook-form.
Related Issues (20)
- issue: explicitly registering input disabled: false boolean value does not trigger validation HOT 8
- issue: `useForm`โs `context` doesnโt update with new values HOT 2
- feat: Add additional Types that do not include the ref in FieldValues
- issue: error disappear once submit clicked HOT 1
- issue: `useFormState` no longer updates `validatingFields` HOT 4
- issue: resetField set option defaultValue not update form default value for that field
- issue: (0 , react_hook_form__WEBPACK_IMPORTED_MODULE_14__.useForm) is not a function
- issue: Incorrect value type from useController for nested field under optional parent field
- issue: async validate method not being awaited
- issue: formState.errors does not update on useForm.trigger HOT 1
- Annotate pre-validated field types
- issue: stale closure of register option onChange. HOT 1
- issue: setting `disabled` in `useForm` with `useFieldArray` immediately marks the field array as dirty HOT 3
- feat: Add the possibility to get the original element reference HOT 1
- issue: watch does not update when using isSubmitted of useController HOT 1
- issue: spyOn useForm not called from version 7.52.2 onwards HOT 1
- issue: useFieldArray does not work correctly when setting disabled in useForm HOT 2
- issue: Field array working slow with @redix-ui
- Add Manual Register/Unregister Control for Controller and useController
- issue: Unexpected ID Reset on useFieldArray with replace HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-hook-form.