[英]Stop an input field in a form from being submitted in react-hook-form in react
我正在與react -hook-form npm package 進行表單驗證。它有 First Name、Last Name、Email、Password 和 Confirm Password 等字段。 當我點擊提交時,它將由useForm ()鈎子中的 handleSubmit 處理。 但我不想在提交表單后獲得的數據中包含確認密碼字段值。
在這里,我分享了我編寫的代碼......
<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>
您可以在 handleSubmit 回調中刪除這些字段:
const onSubmit = (data) => {
delete data.confirmPassword;
alert(JSON.stringify(data));
};
工作示例: https://codesandbox.io/s/react-hook-form-handlesubmit-v7-uqmiy?file=/src/index.jsx:195-230另一個使用取消注冊的選項:
<div>
<label htmlFor="password">Password</label>
<input type="password" {...unregister("password")} placeholder="" />
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.