ValidationSchema = z.object({
AuthenticationBlock: z.object({
ChoiceOfForm: z.enum()
DataBlock: z.discriminatedUnion(ChoiceOfForm, [
z.object({ ChoiceOfForm = 1, empty fields}) //corresponds to the basic form
z.object({ ChoiceOfForm = 2, just username/pw fields) //corresponds to less basic form
z.object({ ChoiceOfForm = 3, user/pw many fields}) //corresponds to advanced form
])
})
})
物件示例:
export type AuthenticationFormValues = {
AuthenticationBlock?: {
choice?: AuthenticationFormChoice | undefined;
data: {
password?: string;
username?: string;
formAuthenticationConfig?: {
formUrl?: string;
javaScriptLoadingDelayInMilliseconds?: number;
forceLogin?: boolean;
customLoginSequence?: string;
authenticationFailed?: FormAuthenticationFailedConfiguration;
};
};
};
};
choiceOfForm是一個 ENUM,對應于 3 個單選按鈕,可折疊不同的表單(1、2 或 3)。我想使用 ZOD 的 discriminatedUnion() 函式來啟用正確的表單驗證塊,具體取決于選擇了哪個choiceOfForm(1,2 或 3)。有沒有辦法將 choiceOfForm 變數傳遞給 discriminatedUnion(choiceOfForm, ...) 來做到這一點?
謝謝
uj5u.com熱心網友回復:
我認為您可以通過以下方式實作您正在尋找的東西:
import { z } from "zod";
enum ChoiceOfForm {
Option1 = 1,
Option2 = 2,
Option3 = 3
}
// Defining this once since it's shared between two of the arms.
const PasswordFields = z.object({
password: z.string(),
email: z.string().email()
});
const schema = z.discriminatedUnion("choice", [
z.object({
choice: z.literal(undefined),
}),
z.object({
choice: z.literal(ChoiceOfForm.Option1)
}),
z.object({
choice: z.literal(ChoiceOfForm.Option2)
}).merge(PasswordFields),
z.object({
choice: z.literal(ChoiceOfForm.Option3),
extraOption: z.number()
}).merge(PasswordFields)
]);
Zod 的discriminatedUnion函式將您要區分的鍵作為第一個引數和聯合的每個“分支”的模式串列。z.literal(undefined)請注意,由于該選項,幾乎所有物件都可以使用此模式成功決議。您可能希望忽略這種可能性,但我不確定您的業務需求。
如果您使用此模式成功決議某些內容,則可以choice使用switchorif陳述句檢查值并縮小型別,就像使用常規可區分聯合一樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/516362.html
標籤:反应打字稿形式佐德
上一篇:讓.NET控制臺應用程式在VisualStudio中讀取secrets.json所需的步驟
下一篇:從0到1設計通用資料大屏搭建平臺
