Skip to content

Commit e2c4a64

Browse files
committed
Added onSubmit.submitJsonData
1 parent a58f164 commit e2c4a64

File tree

6 files changed

+120
-11
lines changed

6 files changed

+120
-11
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ Headlines: Added, Changed, Deprecated, Removed, Fixed, Security
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [Unreleased]
9+
10+
### Added
11+
12+
- `onSubmit.submitJsonData`, to override what's being submitted when dataType is set to `'json'`.
13+
814
## [2.2.1] - 2024-02-16
915

1016
### Fixed

src/lib/client/superForm.ts

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,12 @@ export type FormOptions<
7979
taintedMessage: string | boolean | null | (() => MaybePromise<boolean>);
8080
SPA: true | { failStatus?: number };
8181

82-
onSubmit: (...params: Parameters<SubmitFunction>) => MaybePromise<unknown | void>;
82+
submitOnlyTainted: boolean;
83+
onSubmit: (
84+
input: Parameters<SubmitFunction>[0] & {
85+
jsonData: (data: Record<string, unknown>) => void;
86+
}
87+
) => MaybePromise<unknown | void>;
8388
onResult: (event: {
8489
result: ActionResult;
8590
/**
@@ -593,12 +598,16 @@ export function superForm<
593598
};
594599

595600
async function Form_validate<Schema extends Partial<T>>(
596-
opts: { adapter?: ValidationAdapter<Schema>; recheckValidData?: boolean; formData?: T } = {}
601+
opts: {
602+
adapter?: ValidationAdapter<Schema>;
603+
recheckValidData?: boolean;
604+
formData?: Record<string, unknown>;
605+
} = {}
597606
): Promise<SuperFormValidated<T, M, In>> {
598607
const dataToValidate = opts.formData ?? Data.form;
599608

600609
let errors: ValidationErrors<T> = {};
601-
let status: ValidationResult<Record<string, unknown>> = { success: true, data: dataToValidate };
610+
let status: ValidationResult<Partial<T>>;
602611
const validator = opts.adapter ?? options.validators;
603612

604613
if (typeof validator == 'object') {
@@ -621,9 +630,11 @@ export function superForm<
621630
// need to make an additional validation, in case the data has been transformed
622631
return Form_validate({ ...opts, recheckValidData: false });
623632
}
633+
} else {
634+
status = { success: true, data: {} };
624635
}
625636

626-
const data: T = status.success ? { ...dataToValidate, ...status.data } : dataToValidate;
637+
const data: T = { ...Data.form, ...dataToValidate, ...(status.success ? status.data : {}) };
627638

628639
return {
629640
valid: status.success,
@@ -1493,9 +1504,20 @@ export function superForm<
14931504

14941505
let currentRequest: AbortController | null;
14951506

1496-
return enhance(FormElement, async (submit) => {
1497-
const _submitCancel = submit.cancel;
1507+
return enhance(FormElement, async (submitParams) => {
1508+
let jsonData: Record<string, unknown> | undefined = undefined;
1509+
1510+
const submit = {
1511+
...submitParams,
1512+
jsonData(data: Record<string, unknown>) {
1513+
if (options.dataType !== 'json') {
1514+
throw new SuperFormError("options.dataType must be set to 'json' to use jsonData.");
1515+
}
1516+
jsonData = data;
1517+
}
1518+
};
14981519

1520+
const _submitCancel = submit.cancel;
14991521
let cancelled = false;
15001522
function cancel(resetTimers = true) {
15011523
cancelled = true;
@@ -1534,7 +1556,7 @@ export function superForm<
15341556
let validation: SuperFormValidated<T, M, In> | undefined = undefined;
15351557

15361558
if (!noValidate) {
1537-
validation = await Form_validate();
1559+
validation = await Form_validate({ formData: jsonData });
15381560

15391561
if (!validation.valid) {
15401562
cancel(false);
@@ -1585,7 +1607,7 @@ export function superForm<
15851607

15861608
if (options.SPA) {
15871609
cancel(false);
1588-
if (!validation) validation = await Form_validate();
1610+
if (!validation) validation = await Form_validate({ formData: jsonData });
15891611

15901612
const validationResult = { ...validation, posted: true };
15911613

@@ -1601,12 +1623,12 @@ export function superForm<
16011623

16021624
setTimeout(() => validationResponse({ result }), 0);
16031625
} else if (options.dataType === 'json') {
1604-
if (!validation) validation = await Form_validate();
1626+
if (!validation) validation = await Form_validate({ formData: jsonData });
16051627

16061628
const postData = clone(validation.data);
16071629

1608-
// Move files to form data, since they cannot be serialized
1609-
// will be reassembled in superValidate.
1630+
// Move files to form data, since they cannot be serialized.
1631+
// Will be reassembled in superValidate.
16101632
traversePaths(postData, (data) => {
16111633
if (data.value instanceof File) {
16121634
const key = '__superform_file_' + mergePath(data.path);

src/routes/(v2)/v2/Navigation.svelte

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
'redirect',
2525
'step-form',
2626
'submit-enter',
27+
'submit-json',
2728
'trim-fields',
2829
'unions',
2930
'validate',
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { zod } from '$lib/adapters/zod.js';
2+
import { message, superValidate } from '$lib/server/index.js';
3+
import { schema } from './schema.js';
4+
import { fail } from '@sveltejs/kit';
5+
6+
export const load = async () => {
7+
const form = await superValidate(zod(schema));
8+
return { form };
9+
};
10+
11+
export const actions = {
12+
default: async ({ request }) => {
13+
const formData = await request.formData();
14+
console.log(formData);
15+
16+
const form = await superValidate(formData, zod(schema));
17+
console.log(form);
18+
19+
if (!form.valid) return fail(400, { form });
20+
21+
return message(form, 'Posted OK!');
22+
}
23+
};
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<script lang="ts">
2+
import { superForm } from '$lib/client/index.js';
3+
4+
export let data;
5+
6+
const { form, errors, message, enhance } = superForm(data.form, {
7+
taintedMessage: false,
8+
dataType: 'json',
9+
onSubmit({ jsonData }) {
10+
jsonData({ ...$form, email: 'no-email' });
11+
}
12+
});
13+
</script>
14+
15+
{#if $message}<h4>{$message}</h4>{/if}
16+
17+
<form method="POST" use:enhance>
18+
<label>
19+
Name: <input
20+
name="name"
21+
bind:value={$form.name}
22+
aria-invalid={$errors.name ? 'true' : undefined}
23+
/>
24+
{#if $errors.name}<span class="invalid">{$errors.name}</span>{/if}
25+
</label>
26+
<label>
27+
Email: <input
28+
name="email"
29+
bind:value={$form.email}
30+
aria-invalid={$errors.email ? 'true' : undefined}
31+
/>
32+
{#if $errors.email}<span class="invalid">{$errors.email}</span>{/if}
33+
</label>
34+
<div>
35+
<button>Submit</button>
36+
</div>
37+
</form>
38+
39+
<style lang="scss">
40+
form {
41+
margin: 2rem 0;
42+
43+
input {
44+
background-color: #dedede;
45+
}
46+
47+
.invalid {
48+
color: crimson;
49+
}
50+
}
51+
</style>
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { z } from 'zod';
2+
3+
export const schema = z.object({
4+
name: z.string().min(2),
5+
email: z.string().email()
6+
});

0 commit comments

Comments
 (0)