react hook form onErrors
- Get link
- X
- Other Apps
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:
- Success Callback (onValid) → Executes when form validation passes.
- 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?
- The
onValidfunction runs when validation succeeds. - The
onErrorsfunction runs when validation fails, logging errors to the console. - The error message is dynamically displayed under the input.
- Get link
- X
- Other Apps
Comments
Post a Comment