我对福米克和是的还很陌生。我很困惑为什么在
selectedJobType
验证的条件中将 languages
输入为数组。 jobType
是来自选择框的字符串,所以我希望 selectedJobType
也是一个字符串。相反,它以 any[]
的形式出现。
这是我的代码:
import { MyMultiSelect, MySelect } from "@components/Fields";
import { Formik } from "formik";
import * as Yup from "yup";
interface FormValues {
jobType: string;
languages?: number[];
}
const initialValues: FormValues = {
jobType: "",
languages: [],
};
const validationSchema = Yup.object({
jobType: Yup.string()
.oneOf(["designer", "development", "product", "other"], "Invalid Job Type")
.required("Required"),
languages: Yup.array()
.of(Yup.number().required("Language selection is required"))
.when("$jobType", (selectedJobType, schema) => {
// Why is selectedJobType an array?
console.log("handleChange", field, "isArray:", Array.isArray(value), value);
return selectedJobType[0] === "development"
? schema
.min(1, "At least one language is required for developers")
.required("Language selection is required for developers")
: schema.notRequired();
}),
});
const SignUpForm = () => {
const handleChange = async (
field: string,
value: string | boolean | number | number[]
) => {
// When jobType is selected, it is not an array.
console.log("handleChange", field, "isArray:", Array.isArray(value), value);
};
return (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={() => {}}
>
{(formik) => (
<form onSubmit={formik.handleSubmit}>
<MySelect
label="Job Type"
name="jobType"
required
handleDBSubmit={handleChange}
selectOptions={[
{ value: "designer", label: "Designer" },
{ value: "development", label: "Developer" },
{ value: "product", label: "Product Manager" },
{ value: "other", label: "Other" },
]}
/>
{formik.values.jobType === "development" && (
<>
<MyMultiSelect
label="Known Languages"
name="languages"
handleDBSubmit={handleChange}
required
selectOptions={[
{ value: 0, label: "JavaScript" },
{ value: 1, label: "Java" },
{ value: 2, label: "C" },
{ value: 3, label: "C++" },
]}
/>
</>
)}
</form>
)}
</Formik>
);
};
自定义组件是我配置为与 Formik 一起使用的 MUI AutoComplete 组件。
版本:
我的意思是我使用 zod 基本上相当于 yup,所以我不是专家,但我想它就在这里:
languages: Yup.array()