sveltekit-superforms icon indicating copy to clipboard operation
sveltekit-superforms copied to clipboard

How to construct a schema dynamically?

Open sheldonbaker opened this issue 7 months ago • 1 comments

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?

sheldonbaker avatar Jul 24 '24 15:07 sheldonbaker