首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Yup模式中允许‘null’作为默认值,同时仍然不允许提交‘null’?

如何在Yup模式中允许‘null’作为默认值,同时仍然不允许提交‘null’?
EN

Stack Overflow用户
提问于 2022-06-13 07:40:19
回答 1查看 813关注 0票数 3

我定义了这个Yup模式:

代码语言:javascript
运行
复制
export const ExpectedIncomeSchema = object({
  newIncome: number()
    .required()
    .typeError()
    .min(0)
    .integer(),
  fromDate: date()
    .required()
    .typeError()
    .min(startOfToday()),
});

export type ExpectedIncomeValues = Asserts<typeof ExpectedIncomeSchema>;

现在,我试图在react-hook-form中使用此模式进行验证,并遇到了一个问题,即不允许将defaultValues设置为null""。很明显,因为类型记录说这里唯一允许的类型是numberDate,但我不想将这些值默认为有效值,比如0或随机选择的日期。我希望这些字段最初是空的。

代码语言:javascript
运行
复制
const methods = useForm<ExpectedIncomeValues>({
  resolver: yupResolver(ExpectedIncomeSchema),
  defaultValues: {
    newIncome: null, // <-- only number allowed, so type error in both Typescript and validation
    fromDate: null, // <-- only Date allowed, so type error in both Typescript and validation
  },
);

怎么才能让Yup和打字稿在这里都开心呢?在设置表单时,我希望字段是可空的,但在模式验证之后则不需要。

对此,你有什么聪明的地方吗?还是我必须这样做?

代码语言:javascript
运行
复制
export type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};


export type ExpectedIncomeFormValues = Nullable<ExpectedIncomeValues>;

但是,这方面的一个问题是,错误消息将是“类型错误”消息,而不是我在本例中需要的“必需”消息。

EN

回答 1

Stack Overflow用户

发布于 2022-06-14 12:58:39

下面的内容似乎有效,但不确定它是否真的正确。我意识到yup有两种类型的帮助,TypeOfAsserts.通过将.nullable(true)添加到模式中,第一个将允许null,而第二个将不允许。这就是我想要的。

代码语言:javascript
运行
复制
const schema = object({
  newIncome: number()
    .required()
    .nullable(true)
    .min(0)
    .integer(),
  fromDate: date()
    .required()
    .nullable(true)
    .min(startOfToday()),
});


type ValuesWithNull =
  TypeOf<typeof ExpectedIncomeSchema>;

type ValuesWithoutNull =
  Asserts<typeof ExpectedIncomeSchema>;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72599238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档