Next.js Discord

Discord Forum

Data validation client-side when using server actions

Answered
Forest bachac posted this in #help-forum
Open in Discord
Forest bachacOP
How can I go about this? I want to check client-side prior to submission but what can I do after if the form has an action
Answered by Forest bachac
I ended up using a onSubmit function that cancelled the submission if anything was invalid
View full answer

20 Replies

Netherland Dwarf
Do you mean you want to sanitize or validate the form inputs
In a server action before submitting the data
@Forest bachac
?
If so then you can use zod for example
To validate client side input inside the server. Zod works and integrates well with typescript and react hook form
Forest bachacOP
I wanted to validate the form inputs in the client
Forest bachacOP
I ended up using a onSubmit function that cancelled the submission if anything was invalid
Answer
Forest bachacOP
obv i also validate on the server
Netherland Dwarf
@Forest bachac thats work too, i personally use react-hook-form and zod and the form doesnt submit and display the error for each field i define in the zod schema and i import the same schema in the backend to validate.
Its really useful i find since in zod you can define the type, length and other feature like is a valid email or number etc.
@Forest bachac obv i also validate on the server
Bengal
yeah u dont need to validate on server if ur doing monolithic
@Forest bachac i feel like that sometimes is a waste of server resources
Mugger Crocodile
You need to validate data both in frontend and backend. A user can bypass the frontend and directly send requests to your backend. You can use zod to validate the form data in the server actions. You need not return errors in a human readable format since normal users will never send data directly to your backend, unless you're building an API where you'll have document all the cases.
@Forest bachac thats why i said doing only backend is a waste because its much simpler to check if everything is valid without getting case-specific errors
Mugger Crocodile
The amount of time the server takes to validate each field is negligible for most apps. You can use the same validation logic for both front end and backend but you can show generic errors in the server side, you need not show any case-specific errors. You can use a try catch block to show any generic errors
Netherland Dwarf
@Forest bachac zod is used both frontend and backend
Like invito said