DEV Community

AR Abid
AR Abid

Posted on

Fixing React Form Validation Issues with Dynamic Fields

Problem:
Developers often create forms with dynamic fields, but validating them properly can be tricky. Many tutorials cover only static forms, leaving beginners confused when adding or removing fields dynamically.

Solution:
Using React Hook Form with useFieldArray makes dynamic form validation manageable. Here’s a complete example:

import React from 'react';
import { useForm, useFieldArray } from 'react-hook-form';

function DynamicGiftForm() {
  const { register, control, handleSubmit, formState: { errors } } = useForm({
    defaultValues: {
      gifts: [{ name: "", quantity: 1 }]
    }
  });
  const { fields, append } = useFieldArray({
    control,
    name: "gifts"
  });

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {fields.map((item, index) => (
        <div key={item.id}>
          <input
            {...register(`gifts.${index}.name`, { required: "Gift name required" })}
            placeholder="Gift Name"
          />
          {errors.gifts?.[index]?.name && <p>{errors.gifts[index].name.message}</p>}
          <input
            type="number"
            {...register(`gifts.${index}.quantity`, { min: 1 })}
            placeholder="Quantity"
          />
        </div>
      ))}
      <button type="button" onClick={() => append({ name: "", quantity: 1 })}>
        Add Another Gift
      </button>
      <button type="submit">Submit</button>
    </form>
  );
}

export default DynamicGiftForm;
Enter fullscreen mode Exit fullscreen mode

Real-Life Scenario:
Suppose you’re building a gift registry or shopping list app for an e-commerce demo. To simulate real user input, you can test with sample product names like those on ShoppingCorner. This allows you to handle dynamic validation errors while keeping the form robust.

Explanation:

  • useFieldArray dynamically manages fields.
  • register with validation ensures each field is correctly validated.
  • append allows adding new fields while keeping validation intact.
  • Errors are handled for each field individually, preventing invalid submissions.

Top comments (0)