my react hook form does not trigger validation if I submit form without touching fields
- User
my react hook form does not trigger validation if I submit form without touching fields
- Assistant
As an AI language model, I don't have your complete code and specific scenario to investigate the issue, but here are some general tips:
React Hook Form wouldn't validate the form unless you register the fields via
useFormhook and specify the validation rules. So please make sure that:-
You wrap your form with
useForm()hook. -
You register the inputs via
registermethod in the form with validation rules.
Here is an example code snippet with two required fields
firstNameandlastName:import { useForm } from "react-hook-form"; function App() { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = data => console.log(data); return ( <form onSubmit={handleSubmit(onSubmit)}> <div> <label>First Name</label> <input {...register("firstName", { required: true })} /> {errors.firstName && <span>This field is required</span>} </div> <div> <label>Last Name</label> <input {...register("lastName", { required: true })} /> {errors.lastName && <span>This field is required</span>} </div> <button type="submit">Submit</button> </form> ); } -
- User
I need to trigger validation even if fields are not touched
- Assistant
To trigger validation even if fields are not touched, you can use the
triggermethod provided by React Hook Form on form submission. This method manually triggers the validation for one or more fields.Here's an updated example code snippet that uses
handleSubmitto triggertriggervalidation on form submission:import { useForm } from "react-hook-form"; function App() { const { register, handleSubmit, formState: { errors }, trigger } = useForm(); const onSubmit = data => console.log(data); const submitForm = async () => { try { await trigger(); // trigger validation handleSubmit(onSubmit)(); // submit form if inputs are valid } catch (err) { console.log(err); } }; return ( <form onSubmit={submitForm}> <div> <label>First Name</label> <input {...register("firstName", { required: true })} /> {errors.firstName && <span>This field is required</span>} </div> <div> <label>Last Name</label> <input {...register("lastName", { required: true })} /> {errors.lastName && <span>This field is required</span>} </div> <button type="submit">Submit</button> </form> ); }