使用react formik进行唯一字段验证

时间:2020-05-25 11:16:49

标签: reactjs react-redux formik

我一直在尝试使用react formik为唯一字段实现验证逻辑。到目前为止,我已经尝试了以下方法,但不确定为什么似乎没有显示验证错误或验证逻辑不起作用...

    const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    const uniqueNameValidation = (values) => sleep(2000).then(() => {
       let errors={};
       if (['admin', 'null', 'god'].includes(values.name)) {
          errors.description = 'Nice try';
       }
      return errors;
   });

然后在我的领域中,我正在使用如下功能:

    <div className="form-item">
      <Label htmlFor="Name">Name</Label>
      <Field name="name" className="form-item--name" validate={uniqueNameValidation} />
      {errors.name && touched.name && <div>{errors.name}</div>}
    </div>

有帮助吗? 这也是演示链接... https://codesandbox.io/s/young-violet-12216?file=/src/AddForm.js

0 个答案:

没有答案