sveltekit-superforms
sveltekit-superforms copied to clipboard
How to construct a schema dynamically?
I'd like to have a schema with validations that are dependent on a remote data source, but schemas must be defined outside a load function for caching purposes.
const minLength = 17 // I'd instead like to define this in the load function based on the results of an async api call
// Define outside the load function so the adapter can be cached
const schema = z.object({
name: z.string().default('Hello world!').min(minLength),
email: z.string().email()
});
export const load = (async (event) => {
const properMinLength = await getMinLengthAllowanceForUser(event)
const form = await superValidate(zod(schema)); // can't pass `properMinLength` to an already defined schema
// Always return { form } in load functions
return { form };
});
What's the best way to accomplish this use case? Would it just be to have another schema that extends from the main schema and I additionally superValidate
that in my form action?