React hook form field array validation not working
P粉665679053
P粉665679053 2023-12-06 19:41:46
0
1
386

I have an array of fields with an input field for which I have set some validation rules such as required and minLength.

I want the new field to be validated immediately when it is appended. However, this doesn't happen and even if I append empty fields, the error for these input fields remains undefined:

function App() {
  const useFormMethods = useForm({
    defaultValues: {
      test: [{ firstName: "Bill", lastName: "Luo" }]
    },
    mode: "onChange"
  });
  const { fields, append, remove } = useFieldArray({
    control: useFormMethods.control,
    name: "test",
    rules: {
      minLength: 4
    }
  });

  const onSubmit = (data) => console.log("data", data);

  return (
    <FormProvider {...useFormMethods}>
      <form onSubmit={useFormMethods.handleSubmit(onSubmit)}>
        <h1>Field Array </h1>
        <span className="counter">Render Count: {renderCount}</span>
        <ul>
          {fields.map((item, index) => {
            return (
              <li key={item.id}>
                <FormControlledInput name={`test.${index}.firstName`} />
                <FormControlledInput name={`test.${index}.lastName`} />
                <button type="button" onClick={() => remove(index)}>
                  Delete
                </button>
              </li>
            );
          })}
        </ul>
        <section>
          <button
            type="button"
            onClick={() => {
              append({ firstName: "", lastName: "" });
            }}
          >
            append
          </button>
        </section>

        <input type="submit" />
      </form>
    </FormProvider>
  );
}

This is controlled input that needs to be validated:

export const FormControlledInput = ({ name }) => {
  const {
    control,
    formState: { errors }
  } = useFormContext();

  const { field, fieldState } = useController({
    name,
    control,
    rules: { required: true }
  });

  console.log(`fieldState error: `, fieldState.error);
  console.log(`formState errors: `, errors);

  return <input onChange={field.onChange} value={field.value} />;
};

You can see working code and box examples here. What do I need to do to make it validate every time I change it?

P粉665679053
P粉665679053

reply all(1)
P粉404539732

The append method used to add fields to the array is asynchronous, and the trigger method that performs validation is also asynchronous, so there is a race condition that causes the field to be registered before it is registered with the array. Trigger verification form. You can just await the function result before triggering revalidation when adding an array field.

I forked your CSB here. I also added a useEffect hook that will trigger validation when the component is installed.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!