Description
Today with the @core/zod
plugin, you can generate Zod schema for validating the typing of model entities and the related types for creating, updating, filtering, etc.
The request here is for the additional ability to attach custom field validations, so that the generated schemas can be used for many interesting use cases like form validation, user data upload validation (e.g., csv).
Detailed Thoughts
-
Support of the validation "primitives" offered by Zod, like
length
,email
, etc.For a related note: ZenStack already defines a set of validation attributes that "mirror" Zod's primitives here. However, these are only recognized by access policies, but not Zod generation.
E.g.:
model Foo { email String @email @length(3, 256) age @gt(0, 'age must be positive') }
-
Support for custom validation, like Zod's
refine
orsuperRefine
This can allow validation involving the comparison of fields.
E.g.:
model Foo { x Int y Int @@validate(x > y && y < 100, 'custom error message') }
-
Support for arithmetic operators and data predicate functions
Custom validations can be more flexible if we support arithmetic operations: +-*/, and data functions, like
startsWith
,regex
, etc.
Besides being generated into Zod schema, the @@validate
attribute should also be recognized by ZenStack's policy engine and used to validate data when creating and updating entities at runtime.
Open Questions
-
How do we deal with relation fields used in the validation rules?
model Profile { age Int user User @relation(...) userId @unique } model User { profile Profile @@validate(profile.age > 0) }
We should probably just ban them if we can't see a compelling use case.
-
Potential confusion about different ways of handling validation rules and access policy rules
Access policy rules are compiled to Prisma query syntax and injected at runtime into Prisma queries. E.g.,
@@allow('read', x > 0)
is transformed to{ x: { gt: 0 } }
. This limits what can be allowed for such expressions - they must be able to be expressed in Prisma query. E.g.,@@allow('read', x + y > z)
cannot be transformed.However, validation rules are evaluated in Node.js runtime (with Zod), so theoretically, there's no limit on what it can do.
Having two sets of rules for expressions depending on where they're used can be very confusing IMO.