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>
CodePudding user response:
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>