react hook form onErrors

 why onErrors will be used in react hook form

Why is onErrors Used in React Hook Form?

In React Hook Form, the onErrors callback is used with the handleSubmit function to handle validation errors when the form submission fails. It helps in debugging and displaying custom error messages when a field fails validation.


🔹 How onErrors Works?

When using handleSubmit, you can pass two callbacks:

  1. Success Callback (onValid) → Executes when form validation passes.
  2. Error Callback (onErrors) → Executes when form validation fails.

handleSubmit(onValid, onErrors);

🔹 Example: Handling Errors with onErrors


import { useForm } from "react-hook-form"; export default function App() { const { register, handleSubmit, formState: { errors }, } = useForm(); const onValid = (data) => { console.log("Form Submitted Successfully:", data); }; const onErrors = (errors) => { console.log("Form Errors:", errors); }; return ( <form onSubmit={handleSubmit(onValid, onErrors)}> <input {...register("email", { required: "Email is required" })} placeholder="Email" /> {errors.email && <p style={{ color: "red" }}>{errors.email.message}</p>} <button type="submit">Submit</button> </form> ); }

🔹 What Happens in This Example?

  1. The onValid function runs when validation succeeds.
  2. The onErrors function runs when validation fails, logging errors to the console.
  3. The error message is dynamically displayed under the input.

Comments

Popular posts from this blog

interview questions js[ Anurag Singh ProCodrr]

reactnative_creation