Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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!
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>
);
}
useFormState
for that sweet server action goodness.handleSubmit
is our bouncer, checking IDs before letting data into the club.register
to sign up our inputs for the validation party.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.
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. 🕺💃
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!" };
}
useFormState
.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! 🚀🎉