Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json datatype only validates in a formData object, not a regular object #489

Closed
jdgamble555 opened this issue Oct 20, 2024 · 2 comments
Closed
Labels
documentation Improvements or additions to documentation

Comments

@jdgamble555
Copy link

Description
If I use dataType: 'json' on the client, and pass the data to the server, the data only gets validated if it is a request object, not a regular object.

For example:

const form = await superValidate(request, valibot(mySchema));

This schema has no problems validating. The request object contains a formData object. You can see __superform_json only gets checked using a formData object on this line.

But what if I need to modify the data first?

Example:

const _formData = await request.formData();

// https://github.com/fabian-hiller/decode-formdata
const formData = decode(_formData, {
    arrays: ['tags'],
    files: ['photo']
});

const form = await superValidate(formData, valibot(mySchema));

You can see now the formData is no longer a request object, but a regular parsed object. Now, __superform_json won't get parsed at all.

Since superValidate accepts BOTH a request object and a regular object, so should the json validator. Otherwise, there is no way to modify the form data before passing it to the superValidate function. This means there are NO work arounds.

J

@jdgamble555 jdgamble555 added the bug Something isn't working label Oct 20, 2024
@ciscoheat
Copy link
Owner

If you transform the form data to an object, that's what will be validated, not the request. It could come from a DB or anywhere else.

It's not meant to combine FormData and the __superform_json data (which is encoded with devalue). The validation schema is for one of them, not both.

But if you want to bend the rules, you need to call superValidate twice:

// This will validate __superform_json
const form1 = await superValidate(_formData, valibot(superFormSchema));

// This will validate the transformed FormData
const form = await superValidate(formData, valibot(formDataSchema));

So YES, there are workarounds. 😀

@ciscoheat ciscoheat added documentation Improvements or additions to documentation and removed bug Something isn't working labels Oct 20, 2024
@jdgamble555
Copy link
Author

I think using devalue directly is what I was looking for. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

2 participants