发生验证错误时处理 formik 表单

vin*_*sty 3 reactjs react-native

我在本机代码中有一个 formik 形式,如下所示。可以在以下位置查看完整的可运行链接: here

当前行为:
验证只能用 完成handleSubmit,不能用于处理进一步的操作。请注意,onSubmit如果handleSubmit检测到任何验证错误,则不会触发。

 <Button onPress={handleSubmit} style={styles.button}>
     Submit
 </Button>
Run Code Online (Sandbox Code Playgroud)

预期的解决方案:
在尝试提交(例如:)后验证失败时调用的生命周期事件onValidationError,我可以在其中访问所有输入验证错误道具以进行进一步操作。

例如:我想处理一些事情(比如在验证失败时弹出警报或滚动到第一条错误消息)

代码应该是类似follow 的东西,或者任何其他的方式也可以被接受。只要我可以在发生验证错误时处理事件。

 <Formik
    onSubmit={values => {
       alert(JSON.stringify(values, null, 2));
       Keyboard.dismiss();
    }}
    onValidationError={errorValues => {
       // any action here
       // note that onValidationError is not a built in function
       // but it would be best if it can be achieved this way
       // else any other equivalent solution also can be accepted
    }}
    validationSchema={validationSchema}>
Run Code Online (Sandbox Code Playgroud)

有什么尝试?
我试图在这里集成 2 个解决方案。但未能得到它的工作。
https://github.com/jaredpalmer/formik/issues/1019
https://github.com/jaredpalmer/formik/issues/1484

Mee*_*eri 6

您可以通过绕过您的逻辑在's事件上使用isValidprop(from <Formik>'s render props)作为(文档<form>onsubmit

<form
  onSubmit={e => {
    console.log("isValid", isValid);
    isValid
      ? handleSubmit(e)
      : alert("Handle your custom method instead here");
  }}
>
Run Code Online (Sandbox Code Playgroud)

您可以isValid从 formik 上的渲染道具访问道具

 {props => {
    const {
      values,
      touched,
      errors,
      dirty,
      isSubmitting,
      handleChange,
      handleBlur,
      handleSubmit,
      handleReset,
      isValid // add this to your code
    } = props;
    return ( ... your code );
}}
Run Code Online (Sandbox Code Playgroud)

我也制作了codesandbox,你可以在这里查看工作示例 - https://codesandbox.io/s/trusting-jennings-7wq0f

注意:这在 formik 存储库或任何地方的任何问题上都没有正式提及,但这是submit<form>'sonsubmit事件的自定义方式拦截操作

希望这是有帮助的!