在React -hook-form中有条件地使用YUP设置一个数字字段



我有一个表单,如果选择了某个单选选项,我想呈现一个数字输入框,如果选择了单选选项,这应该是必需的。以下是相关输入的YUP模式:

areSeatsLimited: yup.string().required(),
numOfSeats: yup
.number()
.positive("This field must contain a positive number")
.integer("This field should contain an integer")
.when("areSeatsLimited", {
is: "yes",
then: yup.number().required().typeError("The field must contain a number"),
otherwise: yup.number().notRequired().typeError("The field must contain a number"),
}),

在某种意义上,如果我第一次打开表单并且不选择座位有限的选项,在提交时,我不会从numOfSeats输入中获得错误,这是预期的,因为它不是必需的。

然而,如果我检查座位是有限的,那么它会给我错误,这也是预期的,因为它现在是必需的。但是这里有一个问题:当我再次检查座位是无限的之后选择它们是有限的。它仍然向我抛出错误,好像该字段是必需的。还请注意,它向我抛出了输入错误消息("字段必须包含一个数字")

下面是表单

那部分的react代码
<div className="radio" style={{ display: "block", marginTop: "10px" }}>
<input
value="no"
type="radio"
id="unlimited"
{...register("areSeatsLimited")}
checked={areSeatsLimited === "no" || areSeatsLimited === undefined ? true : false}
/>
<label htmlFor="unlimited">Unlimited</label>
</div>
<div className="radio" style={{ display: "block", marginTop: "10px" }}>
<input
value="yes"
type="radio"
id="limited"
{...register("areSeatsLimited")}
checked={areSeatsLimited === "yes" ? true : false}
/>
<label htmlFor="limited">Limited</label>
</div>
{areSeatsLimited === "yes" ? (
<div className={`form-group required ${errors?.numOfSeats?.message ? "has-error" : ""}`}>
<label htmlFor="numOfSeats">Number Of Seats</label>
<input
type="number"
id="numOfSeats"
className="form-control"
placeholder="Amount of available seats..."
{...register("numOfSeats")}
/>
{errors?.numOfSeats?.message ? (
<span style={{ color: "var(--input-error-text-color)" }}>{errors.numOfSeats.message}</span>
) : (
""
)}
</div>

我有一个类似的字段集,但使用字符串,它按预期工作。

这应该能解决你的问题:

otherwise: number().transform(() => {
return undefined;
}).nullable().notRequired(),

输入字段,根据这个家伙,将返回一个空字符串如果你不提供输入,这就是它抛出typeError的原因。因此,当座位是无限的时候,您需要手动强制它返回undefined。

最新更新