我在用着react-hook-form
with yup
用于我的表单验证并希望某些字段是可选的(空)。
按照他们的文档,我正在使用nullable() and 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"),
});
有什么正确的方法可以做到这一点吗?
你需要使用.when
用于像下面这样的条件验证。我只添加了address
and city
只是,您可以像这样添加其他内容。
export const updateAddressSchema = yup.object().shape({
address: yup.string().when("address", (val, schema) => {
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();
}
}),
city: yup.string().when("city", (val, schema) => {
if(val?.length > 0) {
return yup.string().max(32, "max 32").required("Required");
}
else {
return yup.string().notRequired();
}
}),
}, [
["address", "address"],
["city", "city"],
] //cyclic dependency
);
另外,您还需要添加循环依赖
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)