简体   繁体   English

Formik 是的`.test()` 自定义验证无法正常工作

[英]Formik Yup `.test()` custom validation is not working properly

I created a custom Yup validation using .test() .我使用.test()创建了一个自定义的 Yup 验证。

// users is an array of strings
user: Yup.string().test(
  "user-check",
  "At lease one user should be added",
  () => users.length > 0
)

The goal is to validate the form when at least one user is added.目标是在添加至少一个用户时验证表单。 An input field let you type a username (any string value) then you click a button to add it to a list.输入字段可让您输入用户名(任何字符串值),然后单击按钮将其添加到列表中。

The validation is working well after adding the 2nd username (or adding the 1st one then start typing on the field).添加第二个用户名(或添加第一个用户名然后开始在字段上输入)后,验证运行良好。 I'm sharing this live Demo: https://codesandbox.io/s/hopeful-goldwasser-shpbk我正在分享这个现场演示: https : //codesandbox.io/s/hopeful-goldwasser-shpbk

Steps to reproduce重现步骤

  1. Click on the text field.单击文本字段。
  2. Type a username.输入用户名。
  3. Click the red button.单击红色按钮。

Expected预期的

  • The form should be valid.表格应该是有效的。

What you'll get你会得到什么

  • The form is invalid表格无效

Any feedback about this strange behavior?关于这种奇怪行为的任何反馈?

Remark评论

  • I'm not sure if this is the origin of the problem.我不确定这是否是问题的根源。

  • The first time you add a user, the validation is called 2 times: the 1st time with an empty users array and then with the correct users value (which is the user you added)!第一次添加用户时,验证会调用 2 次:第一次使用空的users数组,然后使用正确的users值(这是您添加的用户)!

The scope of your Formik form currently contains only the input field for a user. Formik 表单的范围当前仅包含用户的输入字段。 The array with users is currently not part of your form (not included in the initial values).带有 users 的数组当前不是表单的一部分(不包含在初始值中)。 There are two thinks you could do:有两种想法你可以这样做:

  const onSubmit = () => {
    if (users.length > 0) {
       // there are some users (form is valid) -> do API call or whatever necessary
    } else {
       // no users (form is not valid) -> display some error
    }
  };

You could even just disable the submit button like this (event it is not the correct way if working with Formik):您甚至可以像这样禁用提交按钮(如果使用 Formik,这不是正确的方法):

<input type="submit" value="Submit" disabled={users.length === 0} />

I hope this helps.我希望这有帮助。 If you have any questions, let me know and I can update my answer.如果您有任何问题,请告诉我,我可以更新我的答案。

尝试用户: Yup.string().test( "user-check", "至少应该添加一个用户", async (users) => await users.length > 0 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM