[英]Formik FieldArray nested object validations with Yup
https://codesandbox.io/s/wonderful-brattain-928gd https://codesandbox.io/s/wonderful-brattain-928gd
Above, I have added some sample code of the problem I am trying to figure out.上面,我添加了一些我试图弄清楚的问题的示例代码。 I am not sure how to map the errors to the correct items in the FieldArray.
我不确定如何将错误映射到 FieldArray 中的正确项目。
In the example, there are yes/no radio buttons which allow a user to indicate whether they have foods they want to add.在示例中,有是/否单选按钮,允许用户指示他们是否有想要添加的食物。 If they select 'yes', the food options appear and they must select at least 1 of the foods and enter its expiration date to fully validate.
如果他们选择“是”,则会出现食品选项,他们必须至少选择 1 种食品并输入其到期日期才能完全验证。
I am trying to add an "expiration" validation error when the users fails to enter an expiration date in the text field.当用户未能在文本字段中输入到期日期时,我试图添加“到期”验证错误。 For example, if I select "Beef" and do not enter an expiration date, the errors populate in the Formik errors.
例如,如果我选择“牛肉”并且没有输入到期日期,则错误会填充在 Formik 错误中。 However, I don't know how to map that error to the correct expiration text box.
但是,我不知道如何将该错误映射到正确的到期文本框。
Any help is appreciated!任何帮助表示赞赏!
Note:笔记:
Validations are only triggered when the validated button is clicked验证仅在单击验证按钮时触发
There is codesandbox and code shown belown:有codesandbox和代码如下所示:
<Form>
<pre
style={{
textAlign: "left"
}}
>
<h3>Data</h3>
{JSON.stringify(values, null, 2)}
<h3>Errors</h3>
{JSON.stringify(errors, null, 2)}
</pre>
<Field
name="food.hasFood"
value
type="radio"
onChange={e => {
setFieldValue("food.hasFood", true);
}}
/>{" "}
Yes
<Field
name="food.hasFood"
value={false}
type="radio"
onChange={e => {
setFieldValue("food.hasFood", false);
}}
/>{" "}
No
{values.food.hasFood && (
<FieldArray name="food.selected">
{arrayHelpers => {
return foodTypes.map(item => (
<div key={item}>
<Field
name={item}
value={item}
type="checkbox"
as={Checkbox}
checked={values.food.selected
.map(f => f.name)
.includes(item)}
onChange={e => {
if (e.target.checked) {
arrayHelpers.push({
name: e.target.value,
expiration: ""
});
} else {
const index = values.food.selected
.map(f => f.name)
.indexOf(e.target.value);
arrayHelpers.remove(index);
}
}}
/>
{item}
{errors.food && touched.food && (
<p>
{Array.isArray(errors.food.selected)
? ""
: errors.food.selected}
</p>
)}
{values.food.selected.map((selectedFood, index) => {
if (item === selectedFood.name) {
return (
<div>
<Field
key={index}
as={TextField}
name={`food.selected[${index}].expiration`}
/>
{console.log(errors)}
{errors.food && touched.food && (
<p>
{Array.isArray(errors.food.selected)
? errors.food.selected[index].expiration
: errors.food.selected}
</p>
)}
</div>
);
}
return null;
})}
</div>
));
}}
</FieldArray>
)}
<button
type="button"
onClick={() => {
validateForm();
}}
>
Validate
</button>
</Form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.