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

Integration with SvelteKit Form Actions #7

Open
CaptainCodeman opened this issue Dec 9, 2022 · 1 comment
Open

Integration with SvelteKit Form Actions #7

CaptainCodeman opened this issue Dec 9, 2022 · 1 comment

Comments

@CaptainCodeman
Copy link
Owner

CaptainCodeman commented Dec 9, 2022

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
Copy link

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

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

No branches or pull requests

2 participants