1

I was doing form validation in react with react-hook-form npm package. It has field like First Name, Last Name, Email, Password and Confirm Password. When I click on submit it will be handled by handleSubmit from useForm() hook. But I don't want to include Confirm Password filed value in the data that I got after submitting the form.

Here I have shared the code that I have written ...

<Grid item xs={12}>
 <TextField
   required
   fullWidth
   name="password"
   label="Password"
   type="password"
   id="password"
   autoComplete="new-password"
   {...register("password", { required: "Required"})}
   error={!!errors.password}
   helperText={errors?.password ? errors.password.message : null}
/>
</Grid>
<Grid item xs={12}>
  <TextField
    required
    fullWidth
    name="confirmPassword"
    label="Confirm Password"
    type="password"
    id="confirmPassword"
    {...register("confirmPassword", { 
      required: "Required",
      validate: (val) => {
      if(watch('password') != val) {
         return "Password does not match"
      }
    }
    })}
    error={!!errors.confirmPassword}
    helperText={errors?.confirmPassword ? errors.confirmPassword.message : null}
 />
 </Grid>

1 Answer 1

3

You can remove those fields in handleSubmit callback:

const onSubmit = (data) => {
        delete data.confirmPassword;
        alert(JSON.stringify(data));
      };

working example: https://codesandbox.io/s/react-hook-form-handlesubmit-v7-uqmiy?file=/src/index.jsx:195-230 another option to use unregister:

<div>
          <label htmlFor="password">Password</label>
          <input type="password" {...unregister("password")} placeholder="" />
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

I found the second one for better code structure and easy to use ... Thanks sharing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.