dynamic validation?

I have a schema like so:
export const blog = type({
headline: "string > 0",
description: "string > 0",
"date_published?": date.or("null"),
date_created: date,
})
export const blog = type({
headline: "string > 0",
description: "string > 0",
"date_published?": date.or("null"),
date_created: date,
})
With this schema i want to do two types of validation. One i dont care if the strings are filled in, they can be empty strings - this is for blogs that are not published. And then two i want to be able to ensure all fields are filled in when the date_published field is filled in because the blog will be published and needs all the required fields. What is the best way to adapt a schema on a prorata basis without duplicating it? Sometimes I dont mind empty strings and sometimes I want the strings to be filled in.
2 Replies
Raqueebuddin Aziz
https://arktype.io/docs/intro/adding-constraints Make your schema for the generic case aka remove the > 0. Then in the narrow function check if datePublished crossed and if it is return false in the narrow function if strings are empty
ArkType
ArkType Docs
TypeScript's 1:1 validator, optimized from editor to runtime
TizzySaurus
TizzySaurus3w ago
You can probably go a step further and use a discriminated union. Something like
type({
data_published: "never | null",
headline: "string"
}).or({
data_published: date,
headline: "string > 0"
})
type({
data_published: "never | null",
headline: "string"
}).or({
data_published: date,
headline: "string > 0"
})
But otherwsie yeah, a narrow would work

Did you find this page helpful?