Formik FieldArray Validation not Validating



Im使用Formik FormArray对象并尝试使用验证似乎不起作用。

  1. 即使有简单的必需验证,也允许提交空字段
  2. 当我添加正则表达式时,它会抛出错误
  3. 我不知道错误消息是否显示
  4. 很难调试

这是我的示例表单的片段(抱歉,它不是完整的代码,而是全部在父容器中(:

const validationSchema = Yup.object().shape({
domains: Yup.array()
.required('Required')
.matches(/^(?!://)([a-zA-Z0-9-_]+.)*[a-zA-Z0-9][a-zA-Z0-9-_]+.[a-zA-Z]{2,11}?$/, {
message: 'Invalid Domain',
excludeEmptyString: true,
})
.matches(/(www.| http: //|https://)/, {
message: 'Should not contain www.| http:// | https://',
excludeEmptyString: true,
})
})
const ErrorMessage = ({ name }) => (
<Field
name={name}
render={({ form }) => {
const error = getIn(form.errors, name)
const touch = getIn(form.touched, name)
return touch && error ? error : null
}}
/>
)
{
({ handleChange, handleBlur, values, errors, touched }) => (
<FormGroup>
<Label>Domains</Label>
<FieldArray
name="domains"
render={arrayHelpers => (
<>
<ul className="list-unstyled">
{values.domains.map((domain, index, domains) => (
<li className="mb-2" key={index}>
<InputGroup>
<Field
name={`domains[${index}]`}
className="form-control"
/>
<InputGroupAddon addonType="append">
<Button
color="primary"
onClick={() => arrayHelpers.remove(index)}
>
<strong>x</strong>
</Button>
</InputGroupAddon>
<ErrorMessage name={`domains[${index}]`} />
</InputGroup>
</li>
))}
<Button
className="mt-2"
color="secondary"
onClick={() => arrayHelpers.push('')}
>
Add a Domain
</Button>
</ul>
</>
)}
/>
</FormGroup>

我试图删除正则表达式验证,但没有奏效。谁能推荐如何做到这一点? 谢谢

https://jaredpalmer.com/formik/docs/api/fieldarray

Forik 站点上对象数组的示例:

const schema = Yup.object().shape({
domains: Yup.array()
.of(
Yup.object().shape({
name: Yup.string()
.min(4, 'too short')
.required('Required'), // these constraints take precedence

用于访问字符串数组:

domains: Yup.array().of(
Yup.string()
.trim()
.required('Required')

我没有添加评论的声誉,但我在 arrayHelper 和 Formik 上也遇到了一些麻烦。域数组中最后一项的初始值是否可能未设置为空字符串?如果你对初始值执行某种类型的获取,它将是比较和数组,该数组缺少你在提交域[${index}]时要包含的最后一个值。因此,根据我的经验,它允许您提交表单,因为它没有初始值,除非您要单击输入,然后将值设置为"或您选择键入的任何内容。

最新更新