[英]Yup validation for multiple checkboxes
const validationSchema = yup.object().shape({
assets: yup.array().min(1).of(yup.string().required()).required(),
});
import { useState } from "react";
import * as yup from "yup";
import { FieldArray, Formik } from "formik";
const initialValues = {
assets: [],
};
const validationSchema = yup.object().shape({
assets: yup.array().min(1).of(yup.string().required()).required(),
});
function Form() {
const [newAsset, setNewAsset] = useState("");
const [assets, setAssets] = useState([
"Property",
"Motor Vehicles",
"Financial Assets",
]);
const handleAddNewAsset = () => {
if (newAsset) {
setAssets([...assets, newAsset]);
setNewAsset("");
}
};
return (
<>
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={(values) => {
console.log("form values if validation succeed: ", values);
}}
>
{(props) => (
<form onSubmit={props.handleSubmit}>
<FieldArray
name="assets"
render={(arrayHelpers) => (
<>
{assets.map((asset, idx) => (
<label className="form-check-label my-1">
<input
name={`assets.${idx}`}
type="checkbox"
className="form-check-input"
value={asset}
checked={props.values.assets.includes(asset)}
onChange={(e) => {
if (e.target.checked) {
arrayHelpers.push(asset);
} else {
const index = props.values.assets.indexOf(asset);
arrayHelpers.remove(index);
}
}}
/>
<span className="mx-2">{asset}</span>
</label>
))}
</>
)}
/>
<input
type="text"
value={newAsset}
onChange={(e) => setNewAsset(e.target.value)}
/>
<button type="button" onClick={handleAddNewAsset}>
Others (specify)
</button>
</form>
)}
</Formik>
</>
);
}
我希望它會有所幫助。 謝謝!
對於問題 1 - 至少應選擇其中一個
試試下面的validationSchema
const validationSchema = Yup.object({checked: Yup.array().min(1, '選擇至少一個您感興趣的選項') });
在 FormIk 中使用 initialValues 如下: <Formik initialValues={{checked: []}} />
對於問題 2 - 其他字段驗證,您可以查看是的 api 文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.