Repository navigation
Composable & dynamic form validation #1049
Replies: 2 comments
|
Sorry for the late replay. I have been very busy the last few days. Can you provide minimal sample code for example via our playground? |
|
For the schema-selection part, you can keep one composed schema if the shipping methods have known shapes: use Here is a minimal delivery/pickup example (Valibot 1.5.0): import * as v from 'valibot';
const CustomerSchema = v.object({
firstName: v.pipe(v.string(), v.nonEmpty()),
lastName: v.pipe(v.string(), v.nonEmpty()),
email: v.pipe(v.string(), v.email()),
});
const AddressSchema = v.object({
line1: v.pipe(v.string(), v.nonEmpty()),
postalCode: v.pipe(v.string(), v.nonEmpty()),
});
const CheckoutSchema = v.variant('shippingMethod', [
v.object({
customer: CustomerSchema,
shippingMethod: v.literal('delivery'),
address: AddressSchema,
}),
v.object({
customer: CustomerSchema,
shippingMethod: v.literal('pickup'),
pickupPointId: v.pipe(v.string(), v.nonEmpty()),
}),
]);
type Checkout = v.InferOutput<typeof CheckoutSchema>;
You can keep these reusable schemas alongside their respective form sections and compose them at the checkout boundary. How you share form state/Field components is a separate, form-library-specific concern; this example doesn't establish the component wiring or when that library revalidates after changing the method. Two details matter here:
I tested this with Valibot 1.5.0 and TypeScript 5.9.3 strict mode: valid delivery/pickup, missing delivery address, empty pickup point, unknown method, invalid customer email, stale inactive address stripping, and the nested Reference: |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hey folks,
I would like to use valibot to power validation of a dynamic form.
Let's say we have a checkout form. The checkout form consists of:
Questions
The form is kinda complicated, so customer info, shipping methods & shipping address rendering, etc. might be organised as separate components. What's the best way to compose the checkout form validation in this case? Should I define a "global" form validation on the checkout component level and then pass Form/Field components down to the specific checkout subcomponents like shipping options?
Can I somehow change the valibot schema based on the currently selected shipping method, so it knows which address fields should be validated/required?
Would appreciate any references to similar examples or docs 🙏
Thank you!
All reactions