TanStackT
TanStack10mo ago
20 replies
sad-indigo

Server Side validation as part of submit: Handling 422 responses

I do not want to use client side validation: My server side mutation (tanstack query) does the validation and responds with a 422 error response which contains the validation errors. This pattern is necessary anyway, when you have validation issues, that might depend on complex database state, which can only be checked in the same transaction you would like to change and commit the data.

However, in the docs I do not see a good way how to do that.

So, as of now I do
mutationQuery.mutate(payload...);

And on the mutationQuery.onError I process the validation error.

When I process the error, when it occurs, I set get the fieldInfo of the field having the error and use setFieldMeta
form.setFieldMeta(actualFieldName, (meta) => {
const error = fieldErrorByFieldNameFromLastError[fieldName];
if (!error) return meta;
return {
...meta,
errorMap: {
...meta.errorMap,
onSubmit: error,
},
};
});



Note, that I use errorMap.onSubmit.

However, this behaves cumbersome.

1) Whatever I set here is not unpacked into field.errors list. It is only present in the errorMap of the field.

2) How can I set validation errors on the form itself, when I have validation errors, that are not mappable to a specific field? There is a form.setErrorMap on the form, but the structure is not really transparent to me.

All this makes me assume, that probably this is altogether not the right way to do it.
Was this page helpful?