How to setValue null to number input? #13067
Unanswered
narbek-abd
asked this question in
Q&A
Replies: 2 comments
|
solution: import * as V from "valibot";
import { useForm } from "react-hook-form";
import { valibotResolver } from "@hookform/resolvers/valibot";
// thanks to https://github.com/fabian-hiller/valibot/issues/1088
function initialNullable<TSchema extends V.GenericSchema>(schema: TSchema) {
return V.pipe(V.nullable(schema), schema);
}
export const schema = V.object({
numberRequired: initialNullable(V.pipe(V.number())),
});
export default function Page() {
const f = useForm<V.InferInput<typeof schema>>({
resolver: valibotResolver(schema),
defaultValues: {
numberRequired: null,
},
});
function setNull() {
f.setValue("numberRequired", null);
}
function onSubmit(body) {
const data = body as V.InferOutput<typeof schema>;
}
} |
0 replies
|
A small typing improvement to the solution above: use RHF's third generic for the validated output, so const schema = V.object({
numberRequired: V.pipe(V.nullable(V.number()), V.number()),
});
const form = useForm<
V.InferInput<typeof schema>,
unknown,
V.InferOutput<typeof schema>
>({
resolver: valibotResolver(schema),
defaultValues: { numberRequired: null },
});
form.setValue('numberRequired', null); // valid editing state
form.handleSubmit(data => {
// numberRequired is number here; no assertion needed
console.log(data.numberRequired);
});The input accepts Resolver input/output generics Prepared with AI assistance. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
if i make this filed V.nullable(), then it's no longer a required filed
All reactions