Skip to content

validationMethod: 'submit-only' does not work when schema has .array().refine(...) property #270

Closed
@ericwong3

Description

@ericwong3

Description
When using client-side validators with validationMethod set to 'submit-only', the validation is triggered unconditionally if the schema contains an array field with .refine() defined. I have made a full MRE on stackblitz below, but the problematic code can be narrowed as below.

Despite having set the validationMethod to submit-only, as the user starts to fill in the text input, the .refine function is immediately called and $allErrors already reports errors on the field, contrarily the input box respects the setting, and only displays "String must contain at least 10 character(s)" on submit.

PS: For my use case, the number array needs to meet some sort of combination requirement so an error only makes sense on the array level, and adding validation before .array() on per element is not a sensible option.

MRE

schema.ts:

import { z } from 'zod';

export const schema = z.object({
  aString: z.string().min(10),
  anArray: z.number().array().default([-1]).refine((arg) => arg.every(n => n >= 0), 'All numbers must >= 0'),
});

+page.server.ts:

import { superValidate } from 'sveltekit-superforms/server';
import type { PageServerLoad } from './$types';
import { schema } from './schema';

export const load = (async () => {
  const form = await superValidate(schema);
  return { form };
}) satisfies PageServerLoad;

+page.svelte:

<script lang=ts>
  import { superForm, superValidate } from 'sveltekit-superforms/client';
  import type { PageData } from './$types';
  import { schema } from './schema';
  import SuperDebug from 'sveltekit-superforms/client/SuperDebug.svelte';
  export let data: PageData;

  const {
    form,
    errors,
    constraints,
    enhance,
    allErrors
  } = superForm(data.form, {
    dataType: 'json',
    validators: schema,
    validationMethod: 'submit-only',
  });
</script>

<form use:enhance method="POST">
  <SuperDebug data={{$form, $allErrors}} />
  <input bind:value={$form.aString}>
  <button>Submit</button>
</form>

Demo: https://stackblitz.com/edit/sveltekit-superforms-1-testing-vqkoi5?file=src%2Froutes%2F%2Bpage.server.ts,src%2Froutes%2F%2Bpage.svelte

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingconfirmedConfirmed bug, will be worked upon in a near release.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions