CaptainCodeman / svelte-form-helper

Lightweight helpers for form validation with Svelte
https://captaincodeman.github.io/svelte-form-helper/
MIT License
55 stars 0 forks source link

Integration with SvelteKit Form Actions #7

Open CaptainCodeman opened 1 year ago

CaptainCodeman commented 1 year ago

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.

christophsturm commented 1 year ago

this looks very exciting, a demo with client and server side validation maybe using zod would be very cool.