T
TanStack14mo ago
stormy-gold

Search params start and end date validation

Hi there, im implementing search params for filters and i want to make sure the start date is before the end date. in zod i can do something like this
export const FiltersRequest = object({
startDate: fallback(string().date(), '').default(''),
endDate: fallback(string().date(), '').default(''),
}).refine((data) => {
const startDate = parseDate(data.startDate)
const endDate = parseDate(data.endDate)
return startDate.compare(endDate) > 0
}, {
path: ["startDate"],
message: "Start date must be before end date",
});
export const FiltersRequest = object({
startDate: fallback(string().date(), '').default(''),
endDate: fallback(string().date(), '').default(''),
}).refine((data) => {
const startDate = parseDate(data.startDate)
const endDate = parseDate(data.endDate)
return startDate.compare(endDate) > 0
}, {
path: ["startDate"],
message: "Start date must be before end date",
});
But this doesn't work with the fallback since it would fall after the fallback.
3 Replies
stormy-gold
stormy-goldOP14mo ago
Would this be a nice work around?
export const FiltersRequest = object({
startDate: fallback(string().date(), '').default(''),
endDate: fallback(string().date(), '').default(''),
}).transform((data) => {
if (parseDate(data.startDate).compare(parseDate(data.endDate)) > 0) {
return {
startDate: data.endDate,
endDate: data.startDate
}
}
return data
});
export const FiltersRequest = object({
startDate: fallback(string().date(), '').default(''),
endDate: fallback(string().date(), '').default(''),
}).transform((data) => {
if (parseDate(data.startDate).compare(parseDate(data.endDate)) > 0) {
return {
startDate: data.endDate,
endDate: data.startDate
}
}
return data
});
flat-fuchsia
flat-fuchsia14mo ago
what should be the fallback behavior if start is not before end?
stormy-gold
stormy-goldOP14mo ago
already made a work around for now, i switch the endDate with startDate if it becomes before the startDate. Really appreciate your work on Tanstack router and especially the quick responses on Discord and Github of the team.

Did you find this page helpful?