Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

React 19 Form Validation: When useFormState Meets React-Hook-Form

Alright, React ninjas! 🥷 You’ve mastered the basics of useFormState, but now it’s time to level up. We’re talking form validation that’s tighter than a drumhead and smoother than buttered silk. Ready to make your forms bulletproof? Let’s dive in!

The Dream Team: useFormState + React Hook Form 🦸‍♀️🦸‍♂️

Picture this: the raw power of useFormState combined with the finesse of React Hook Form. It’s like peanut butter and jelly, but for code. Let’s see how these two can tango:

"use client";
import { useFormState } from "react-dom";
import { useForm } from "react-hook-form";
import { onFormPostAction } from "./formPostAction";

export default function SuperForm() {
  const [state, action] = useFormState(onFormPostAction, { message: "" });
  const { register, handleSubmit, formState: { errors } } = useForm();

  const onSubmit = handleSubmit((data) => {
    const formData = new FormData();
    Object.entries(data).forEach(([key, value]) => formData.append(key, value));
    action(formData);
  });

  return (
    <form onSubmit={onSubmit}>
      <div>{state.message}</div>
      <input {...register("username", { required: "Username is required" })} />
      {errors.username && <p>{errors.username.message}</p>}
      <button type="submit">Submit</button>
    </form>
  );
}

Breaking It Down Like a DJ 🎧

  1. We’re still rocking useFormState for that sweet server action goodness.
  2. Enter React Hook Form, stage left. It’s bringing the validation heat.
  3. handleSubmit is our bouncer, checking IDs before letting data into the club.
  4. We’re using register to sign up our inputs for the validation party.
  5. Errors? We display them faster than you can say “Oops!”

The Secret Sauce: Custom Submit Handler 🥫

See that onSubmit function? It’s the glue that holds our React Hook Form and useFormState worlds together. It’s like a translator that speaks both languages fluently.

Validation Rules: Because Chaos is So Last Season 🎭

Want to add more validation rules? React Hook Form’s got your back:

<input {...register("email", {
  required: "Email is required",
  pattern: {
    value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
    message: "Invalid email address"
  }
})} />
{errors.email && <p>{errors.email.message}</p>}

Now your form is checking emails like a bouncer at an exclusive tech party. 🕺💃

Server-Side Validation: Trust No One 🕵️‍♂️

Remember, client-side validation is just the first line of defense. Always validate on the server too:

"use server";

export async function onFormPostAction(prevState, formData) {
  const username = formData.get("username");
  if (!username || username.length < 3) {
    return { message: "Username must be at least 3 characters long" };
  }
  // More validation and processing...
  return { message: "Form submitted successfully!" };
}

The Grand Finale: Putting It All Together 🎭

  1. Client-side validation catches the obvious stuff.
  2. Data passes the vibe check? Send it to the server.
  3. Server does its own validation (trust issues, you know?).
  4. Results flow back through useFormState.
  5. User sees the outcome faster than a React re-render.

Wrapping Up: You’re Now a Form Validation Guru 🧘‍♂️

Congrats, hotshot! You’ve just merged the powers of useFormState and React Hook Form like a coding alchemist. Your forms are now tighter than stadium security at a Taylor Swift concert.

Remember, with great power comes great responsibility… to create forms that are both user-friendly AND bulletproof. Now go forth and validate like the code warrior you are! 💻🛡️

Happy coding, you magnificent validation virtuoso! 🚀🎉

Leave a Reply

Your email address will not be published. Required fields are marked *