Skip to content

Integration with SvelteKit Form Actions #7

@CaptainCodeman

Description

@CaptainCodeman

It should be easy to integrate with SvelteKit Form Actions so a single set of validation errors can be used for both client-side and server-side validation.

It should just be a case of setting the initial validation state from the ActionData returned from the server, probably a case of "use the standard ValidityState flags when returning the state on the server")

So instead of the example in the SK docs:

if (!email) {
  return fail(400, { email, missing: true });
}
<input name="email" type="email" value={form?.email ?? ''}>
{#if form?.missing}<p class="error">The email field is required</p>{/if}
{#if form?.incorrect}<p class="error">Invalid credentials!</p>{/if}

It should return the validation errors for each field using the standard validation flags:

if (!email) {
  return fail(400, { email: { value: email, valueMissing: true } });
}

And on the client we'd probably do something like:

export let form: ActionData

const form_validator = createForm()
const email = form_validator.field({ state: form.email })

Then the hints setup for client-side validation could be re-used:

{#if $email.valueMissing}Email address is required{/if}
{#if $email.typeMismatch}Not a valid email address{/if}
{#if $email.customError}Invalid credentials{/if}

Obviously, the form couldn't be submitted if it fails to verify with the standard inbuilt browser validations, but it's useful to be able to re-used state and it's possible that one POST happened to not load the JS and another one does, so this should work with either.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions