Useful or not, from you.
zod Contextual validations

I'm looking for a way to validate in different ways in different contexts. For example, take a complex object on the client (browser) with foreign-key fields (IDs) that map to other objects on the backend. The client has a mechanism for retrieving these IDs and naturally trusts them. The client also may not have a reasonable mechanism for validating them. On the server, we don't trust these to be valid IDs by default. We need to ensure that they map to real objects.

How would we share most of the schema, but have slightly differing validations in different contexts?

From a high level, I'm thinking of a context object that can be passed down and used in the validators similar to how a lot of GraphQL server implementations work.

That's a useful answer
Without any help

It seems to me that patching could get out of hand pretty quickly. Like if you have something like object -> union -> object -> string with custom validations, how would you readily do a deep patch to target the string but not on other variants in the union? It seems like that would get pretty complex both on the implementation side, and might be hard to follow on the application side. This is why I'm wondering if my suggestion in is the right approach.

What kind of tool do you see on top of zod? Are you envisioning a library that define the structure and create a zod schema based on that, or would it be more application logic? I guess it's not clear if zod should be considered a low-level primitive, or if it's something that applications would more commonly depend on directly. If it is a low-level primitive, guidance on the best ways to create tools on top of it would be helpful.

What I mean by "different contexts" is less about how or where the schema is used, but on a conceptual level. There may be validations that can not or should not be run in some circumstances. A couple examples:

  • Validations that only the server can do because of access to resources.
  • Validations with a CPU performance hit, so the validations need to be debounced, run on field blur, form submission, etc so as to not drop frames
  • Validations that call out to the backend (assuming #87 is done) need to be debounced, run on field blur, form submission, etc so as to preserve server resources/bandwidth/etc

So for a full-stack example, there could be 3+ schemas in operation with lots of shared logic:

  • API validations
  • Validations that happen frequently on user input
  • Validations that happen infrequently on the client