Monday 30 November 2020

How to validate multistep form in react

I have a multi-step form, which I am making using react, to work on validation I am using react-hook-form.

I have already achieved 90% of things just one thing I am facing the issue is getting the second form data which is dynamic.

What I am doing is

  • In my first form I have two fields when those are filled (validated) I am going to the next form
  • In my next form I have two input fields and on the add button user can add multiple rows of fields as well and these are working fine

issue

  • Now when I create new fields in the second form I want to validate them but not getting an idea how can I do that.

What I have done

In my main component, I am doing this for validation

const forms = [
  {
    fields: ['desig', 'dept'],
    component: () => (
      <Pro register={register} errors={errors} defaultValues={defaultValues} />
    ),
  },
  {
    fields: [
      `userInfo[0].fname`, // here I am facing issue if I am statically putting 0,1 then it is validating that perticular form
      `userInfo[0].sirname`,
    ],
    component: () => (
      <Basic
        register={register}
        errors={errors}
        defaultValues={defaultValues}
        inputHolder={inputHolder}
        deleteRow={deleteRow}
        addRow={addRow}
      />
    ),
  },
];

On click of submitting, I am doing this

const handleSubmit = (e) => {
  triggerValidation(forms[currentForm].fields).then((valid) => {
    if (valid) {
      console.log('whole form data - ', JSON.stringify(defaultValues));
    }
  });
};

and here i want data as like below if two data is added in form2

    {
  "fname": "dsteve",
  "sname": "smith",
  "userInfo": [
    {
      "desig": "ddd",
      "dept": "deptee"
    },
    {
      "desig": "ddd",
      "dept": "deptee"
    }
  ]
}

I have done everything but here only I have been stuck, I know where the issue is

Instead of this

fields: ["fname", "sname"],

I have to do like this

fields:[`userInfo[0].name, `userInfo[0].sname],

This 0-1 I have to make dynamic as per indexes, I don't know what I am missing

I tried mapping the fields with index through inputHolderbut it did not work

Edit / Update

If I am doing like this

fields:[`userInfo[0].name`,`userInfo[1].name`, `userInfo[0].sname`,`userInfo[1].sname],

So it is taking validation for two fields, but that is manually I am doming, if user creates more fields then that should take these fields dynamically.

Here is my code sandbox, which contains the full code

Here is my code sandbox



from How to validate multistep form in react

No comments:

Post a Comment