I am facing a challenge in validating form data before sending it to a server. I want to set the form action property to a function that can validate the data on the client side and then trigger the formAction if everything checks out. However, I am struggling with how to pass data from the form action to the function and back to the formAction function. My project uses next.js with typescript, and I would like to utilize a form state with a formState variable. The issue arises when calling formAction without any arguments, even though I need to provide my form data. How can I effectively pass data to the validateData function and subsequently to formAction? I am currently using next.js version 14.2.5, along with react and react-dom 18.2.
Below is a simplified version of the problem I am encountering.
"use client";
import { useFormState } from "react-dom";
import farServerFunction from "./func.ts";
export default function Page() {
const [formState, formAction] = useFormState(farServerFunction, null);
const validateData = (data: FormData) => {
const name = data.get("name") as string;
if (name.length < 5) {
alert("Name must be at least 5 characters long.");
return;
}
formAction(data); // Expected 0 arguments, but got 1
}
return <form action={validateData}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>;
}
I have attempted to research this issue online, including using chatGPT and consulting documentation, but I still find it confusing and lacking sufficient clarity.