我需要根据单选按钮值验证我的字段。这是我的问题示例代码我的单选按钮值为第一个单选按钮->values.type==";PO";第2个单选按钮->values.type==";PRE";
这是我的验证类
import * as Yup from "yup";
const POValidation = Yup.object().shape({
purchaseOrderNumber: Yup.object()
.required("This field is Required"),
amount: Yup.number()
.required("This field is Required")
.typeError("Amount is required"),
number: Yup.string()
.required("This field is Required"),
term: Yup.object()
.required("This field is Required")
});
export { POValidation };
当用户选择第一个单选按钮时,values.type==";PO";,金额字段必须是强制性的,当用户选择第2个单选按钮值时;PRE";,术语字段必须是强制性的。我如何将这些条件应用于我的验证类?感谢
根据您的问题,您希望在"类型";。
以下是您可以尝试的代码示例:
import * as Yup from "yup";
const POValidation = Yup.object().shape({
type: Yup.string()
.required("Please select type.")
.default("default type"),
amount: Yup.number()
.when("type", {
is: (isData) => {
return (
isData === "PO"
);
},
then: (thendata) => {
return (
Yup.number()
.required("Please select amount.")
.test({
message: "Too Short!",
test: (value) => {
return value >= 1;
},
})
.default("default amount")
.nullable()
);
},
})
.nullable(),
term: Yup.number()
.when("type", {
is: (isData) => {
return (
isData === "PRE"
);
},
then: (thendata) => {
return (
Yup.number()
.required("Please select term.")
.test({
message: "Too Short!",
test: (value) => {
return value >= 1;
},
})
.default("default term")
.nullable()
);
},
})
.nullable()
});
export { POValidation };
您需要添加一个值来存储RadioButton
,我称之为radioValue
。您需要的最新POValidation
如下:
...
amount: Yup.number().when("radioValue", {
is: (value) => value=== "PO",
then: Yup.number()
.required("This field is Required")
.typeError("Amount is required"),
}),
term: Yup.object().when("radioValue", {
is: (value) => value=== "PRE",
then: Yup.object().required("This field is Required"),
}),
...