最终表单数组字段异步验证

时间:2018-12-07 12:09:24

标签: reactjs react-final-form final-form react-final-form-arrays

我正在尝试实现异步验证react-final-form-array。但是它返回的承诺却丝毫不显示错误。

我参考了this代码以进行asnyc验证,并使用最终表单数组here创建了自己的版本。

表格:

<Form
  onSubmit={onSubmit}
  mutators={{
    ...arrayMutators
  }}
  initialValues={{ customers: [{ placeholder: null }] }}
  validate={formValidate}
  render={({
    handleSubmit,
    mutators: { push, pop }, // injected from final-form-arrays above
    pristine,
    reset,
    submitting,
    values,
    errors
  }) => {
    return (
      <form onSubmit={handleSubmit}>
        <div>
          <label>Company</label>
          <Field name="company" component="input" />
        </div>
        <div className="buttons">
          <button type="button" onClick={() => push("customers", {})}>
            Add Customer
          </button>
          <button type="button" onClick={() => pop("customers")}>
            Remove Customer
          </button>
        </div>
        <FieldArray name="customers" validate={nameValidate}>
          {({ fields }) =>
            fields.map((name, index) => (
              <div key={name}>
                <label>Cust. #{index + 1}</label>
                <Field
                  name={`${name}.firstName`}
                  component={testInput}
                  placeholder="First Name"
                />
                <Field
                  name={`${name}.lastName`}
                  component={testInput}
                  placeholder="Last Name"
                />
                <span
                  onClick={() => fields.remove(index)}
                  style={{ cursor: "pointer" }}
                >
                  ❌
                </span>
              </div>
            ))
          }
        </FieldArray>

        <div className="buttons">
          <button type="submit" disabled={submitting || pristine}>
            Submit
          </button>
          <button
            type="button"
            onClick={reset}
            disabled={submitting || pristine}
          >
            Reset
          </button>
        </div>
        <pre>
          nameValidate Function:{"\n"}
          {JSON.stringify(nameValidate(values.customers), 0, 2)}
        </pre>
        <pre>
          Form errors:{"\n"}
          {JSON.stringify(errors, 0, 2)}
        </pre>
        <pre>
          Form values:{"\n"}
          {JSON.stringify(values, 0, 2)}
        </pre>
      </form>
    );
  }}
/>

验证功能

const duplicateName = async value => {
  await sleep(400);
  if (
    ~["john", "paul", "george", "ringo"].indexOf(value && value.toLowerCase())
  ) {
    return { firstName: "name taken!" };
  }
};

const nameValidate = values => {
  if (!values.length) return;

  const errorsArray = [];

  values.forEach(value => {
    if (value) {
      let errors = {};

      if (!value.firstName) errors.firstName = "First Name Required";
      if (Object.keys(errors).length === 0) {
        errors = duplicateName(value.firstName);
        console.log("errors", errors);
      }
      errorsArray.push(errors);
    }
  });

  return errorsArray;
};

1 个答案:

答案 0 :(得分:1)

好的,您正在以不允许的方式混合验证。您不能将Promise嵌入到一系列错误中,整个验证功能必须返回一个Promise。 Here's the fixed versionawait duplicateName()是重要的一环。

const nameValidate = async values => {
  if (!values.length) return

  return await Promise.all(
    values.map(async value => {
      let errors = {}
      if (value) {
        if (!value.firstName) errors.firstName = 'First Name Required'
        if (Object.keys(errors).length === 0) {
          errors = await duplicateName(value.firstName)
        }
      }
      console.error(errors)
      return errors
    })
  )
}