How to retrieve validated values from createServerValidate in Next.js? #778
-
The documentation shows how to perform server-side validation in Next.js using Server Actions which works as expected. However, how do you retrieve the validated data after the validation has succeeded? And how should you return an error outside of the Furthermore, how would you integrate Zod or other validators in |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
Let's tackle these one-by-one :) Handle Validated Data Post Validate
You don't! At least not from our API. You parse Add More Errors
You would add the form error to the // From the action.ts
return {formState: validatedFields}; // From client-component.tsx
const [state, action] = useActionState(someAction, {formState: initialFormState})
const {formState} = state;
const form = useForm({
...formOpts,
transform: useTransform((baseForm) => mergeForm(baseForm, formState), [formState]),
}) Zod Integration
This is more straightforward than you might think: // shared-code.ts
export const formOpts = formOptions({
defaultValues: {
firstName: '',
age: 0,
},
validatorAdapter: zodAdapter()
}) // action.ts
const serverValidate = createServerValidate({
...formOpts,
onServerValidate: z.object({/*...*/})
}) You can even: // shared-code.ts
export const schema = z.object({/*...*/});
export const formOpts = formOptions({
defaultValues: {
firstName: '',
age: 0,
},
validatorAdapter: zodAdapter(),
validators: {
onChange: schema
}
}) // action.ts
const serverValidate = createServerValidate({
...formOpts,
onServerValidate: schema
}) Please Review This PR :)We have a note to improve the PR DX like so: What do you think? Better or worse? |
Beta Was this translation helpful? Give feedback.
-
@crutchcorn but we cant use this:
with this:
|
Beta Was this translation helpful? Give feedback.
-
@CarelessInternet , are you able to share your code? |
Beta Was this translation helpful? Give feedback.
Let's tackle these one-by-one :)
Handle Validated Data Post Validate
You don't! At least not from our API. You parse
formData
again manually using your tool of choice. I would suggest using the same as we do internally (decode-formdata
), but you can use any tool you'd like.Add More Errors
You would add the form error to the
onServerValidate
behavior ideally. You want your non-form validation to occur outside of theserverValidate
function call. If you wanted to pass state to the client beyond the serv…