Skip to content

Reparse against the output of a Schema (codecs)Β #5377

@Sparticuz

Description

@Sparticuz

It would be helpful to provide a way to re-parse the output of a schema, specifically when working with Codecs.

I pull data from my database and encode it for use in my (react-hook-) form. The user can then edit data as needed in the form, then submits the form, which gets validated using the zodResolver. If successful, the data is passed back to the server, where it's parsed again and committed to the database.

The biggest issue with working with html forms has been the difficulty with Numbers, so I wanted a codec that would encode the number to a string, then decode it back to an int (or float in places). I got encode working great, it's passing strings to my client. However, when the form submits, it submits the parsed data, which is a number. (I don't think it's that great of an idea to submit the non-parsed data). When I try to verify the data that was sent from the client, because it's already been parsed, the field is a number already and is failing with 'expected string'.

I would like to request a way to parse against the output of the codec.

const schema = z.object({
  num: z.codec(z.string().regex(z.regexes.integer), z.int(), {
    decode: (str) => Number.parseInt(str, 10),
    encode: (num) => num.toString(),
  })
});

should be able to reparse and pass with the data satisfying the second parameter of z.codec.

The workarounds that I see is const reparseSchema = schema.omit({ num: true }).extend({ num: z.int() });
However, this requires me to have the schema defined twice.

My request:

await schema.reparseAsync({ num:42 })

Related to #5081 but that was closed before codecs were a thing

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions