You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
enumFilters{CATEGORY='category',PRICE='price'}constallowedFilters=Object.values(Filters).join('|');// RegExp accepts just the filter key (i.e. `category`)// or the filter key followed by the sub-filter (i.e. `category_cuisine`)// (It's not validating the sub-filter to simplify)constkeyPattern=newRegExp(`^(${allowedFilters})(?:_\\w+)?$`,'u');constFilterSchema=z.record(z.string().regex(keyPattern),z.array(z.string()).or(z.string()));
That works as expected, but I have an issue: some extra query parameters, like page and sort, must be validated.
Creating a union fails because these extra parameters would first fail in the above RegExp.
// FailsconstUrlSchema=z.union([FilterSchema,// ← Fails here first, since `page` is invalid for the RegExpz.strictObject({page: z.string().optional(),sort: z.string().optional()})]);
I had two ideas to work around that, but neither one worked.
The first one was to preprocess, isolate the filters, validate, and merge them again:
Both didn't work, and I'm starting to accept that there's no easy way to do this. I ended up extending the RegExp to include page and sort, but now I want to understand if there's a better way to do this.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hi there!
I'm validating filters and sub-filters in a URL.
For example:
These filters live in the URL, like so:
?category=restaurant&category_cuisine=italian
I'm trying to use Zod to validate that.
This is my main idea:
That works as expected, but I have an issue: some extra query parameters, like
page
andsort
, must be validated.Creating a union fails because these extra parameters would first fail in the above RegExp.
I had two ideas to work around that, but neither one worked.
The first one was to
preprocess
, isolate the filters, validate, and merge them again:And the second one was to
refine
inFilterSchema
, returningtrue
to the non-filter ones and expecting them to fail in thestrictObject
validation:Both didn't work, and I'm starting to accept that there's no easy way to do this. I ended up extending the RegExp to include
page
andsort
, but now I want to understand if there's a better way to do this.Beta Was this translation helpful? Give feedback.
All reactions