我正在使用react-hook-formwithyup進行表單驗證,并希望某些欄位是可選的(null)。
按照他們的檔案,我正在使用nullable(),optional()但它仍在得到驗證:
export const updateAddressSchema = yup.object({
address: yup
.string()
.nullable()
.optional()
.min(5, "Address must be more than 5 characters long")
.max(255, "Address must be less than 255 characters long"),
city: yup
.string()
.nullable()
.optional()
.max(32, "City name must be less than 32 characters long"),
postal_code: yup
.string()
.nullable()
.optional()
.length(10, "Postal code must be 10 characters long"),
phone: yup
.string()
.nullable()
.optional()
.min(10, "Phone number must be more than 10 characters long")
.max(20, "Phone number must be less than 20 characters long"),
});
有什么正確的方法可以做到這一點嗎?
uj5u.com熱心網友回復:
您需要使用.when如下所示的條件驗證。我只為address而且city只添加了,您可以為其他類似的添加。
export const updateAddressSchema = yup.object().shape({
address: yup.string().when("address", (val, schema) => {
if (val) {
if(val.length > 0) { //if address exist then apply min max else not
return yup.string().min(5, "min 5").max(255, "max 255").required("Required");
} else {
return yup.string().notRequired();
}
} else {
return yup.string().notRequired();
}
}),
city: yup.string().when("city", (val, schema) => {
if (val) {
if(val.length > 0) {
return yup.string().max(32, "max 32").required("Required");
}
else {
return yup.string().notRequired();
}
} else {
return yup.string().notRequired();
}
}),
}, [
["address", "address"],
["city", "city"],
] //cyclic dependency
);
此外,您需要添加回圈依賴
uj5u.com熱心網友回復:
非常感謝@Usama 的回答和解決方案!
我在使用他們的解決方案時遇到了另一個問題。如果提交了空值,我的后端 API 會忽略空值并回傳前一個值。問題在于,在初始渲染時,文本欄位的值為 null,但在選擇并鍵入然后洗掉鍵入的字母以使其再次為空(不提交)后,其值將變為空字串,因此我的 API 會拋出錯誤并且不會更新用戶資訊。
我設法修復它的方法是使用yup'.transform()方法將型別從空字串轉換為 null 如果未填充文本欄位:
export const updateAddressSchema = yup.object().shape(
{
address: yup.string().when("address", (value) => {
if (value) {
return yup
.string()
.min(5, "Address must be more than 5 characters long")
.max(255, "Address must be less than 255 characters long");
} else {
return yup
.string()
.transform((value, originalValue) => {
// Convert empty values to null
if (!value) {
return null;
}
return originalValue;
})
.nullable()
.optional();
}
}),
......................
},
[
["address", "address"],
......................,
]
);
我真的希望這對某人有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/484246.html
標籤:javascript html 反应 验证 对
下一篇:如果相鄰單元格為空,則拒絕輸入
