Zod allow all keys matching regex

I’m using zod to validate some data, and I want to allow certain attributes, as well as any attribute with key matching /metadata_hash_.*/.

Say for example this schema:

import { z } from "zod";

const schema = z.object({
  a: z.number(),
  b: z.number()
});

Now I want to allow any attribute matching /metadata_hash_.*/. I’ve tried:

  • Merging with a record object, but that was not allowed
  • using .catchall, but I did not find a way to check the key, only the value
  • using z.preprocess and converting the keys into an object and validating that as a z.record(z.string().refine(...), z.string()),
    but this changes the shape of the object which I don’t really want.

Is there a good way to do this?