1.6.1 • Published 9 months ago

@nerd-coder/svelte-zod-form v1.6.1

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

🌵 Svelte Zod Form

jsr npm workflow licensebundle]bundle-linkcodecov]codecov-link

Building forms in Svelte with breeze, using Zod

Example

REPL: Simple login form REPL: Simple login form

Installation

NPM

npm i @nerd-coder/svelte-zod-form

JSR (Recommended)

npx jsr add @nerd-coder/svelte-zod-form

How to use

First you need to create a Zod's schema

import { z } from 'zod'

const loginSchema = z.object({
  email: z.string().email(),
  pass: z.string().min(4),
})

Then pass the schema to ZodFormStore:

const form = new ZodFormStore(loginSchema, { onSubmit: v => console.log('Submitted values:', v) })

All the field's handler, value will be generated and typed for you:

// We need pull the generated field store out, in order
// to use the Svelte's "auto subscription" feature "$"
const { email_value, email_error, email_dirty, pass_value, pass_error, pass_dirty } = form.stores

Finally, use it in html

<form on:submit|preventDefault={form.triggerSubmit}>
  <fieldset>
    <input
      name="email"
      on:input={form.fields.email.handleChange}
      on:blur={form.fields.email.handleBlur}
      value={$email_value || ''}
      class:invalid={!!$email_error}
      class:valid={!$email_error && !!$email_dirty}
    />
    {#if $email_error}<p>{$email_error}</p>{/if}
  </fieldset>

  <fieldset>
    <input
      name="pass"
      type="password"
      on:input={form.fields.pass.handleChange}
      on:blur={form.fields.pass.handleBlur}
      value={$pass_value || ''}
      class:invalid={!!$pass_error}
      class:valid={!$pass_error && !!$pass_dirty}
    />
    {#if $pass_error}<p>{$pass_error}</p>{/if}
  </fieldset>

  <button type="submit">Sign In</button>
</form>

Configuration

initialValue

  • type: Partial<T>
  • required: false
  • default: undefined

The initial data in the form. Will revert to this value if call form.reset.

const form = new ZodFormStore(schema, {
  initialValue: { email: 'my@email.com' },
  ...
})

onSubmit

  • type: (v: T) => Promise<void | string> | string | void
  • required: true

Async callback to handle submmition of the form. Should return nothing, or an string contain error message

const form = new ZodFormStore(schema, {
  onSubmit: (values) => console.log('Submitted values:', values),
  ...
})

debug

  • type: boolean
  • required: false
  • default: false

Print various debug messages.

const form = new ZodFormStore(schema, {
  debug: true,
  ...
})

API

PropTypeDescription
modelReadable<T>Form's data. Will be passed to onSubmit handler
optionsreadonly ZodFormStoreOptions<T>Form settings. Should not be update
triggerSubmit() => Promise<void>Function to start parsing, validating and submit the form's data
setupAutoSubmit(delay: number) => UnsubscriberSetup auto submit on every change of the model
reset() => voidFunction to reset the form to original state.
submittingReadable<boolean>True of submitting the form.
errorReadable<string>Error message returned from onSubmit handler, or custom validation message.
errorsReadable<string[]>Array of string contains all error messages (including fields's errors and error return from onSubmit handler).
dirtyReadable<boolean>Indicate if the form is edited or submitted.
validReadable<boolean>Indicate if the form is valid.
fieldsobjectGenerated fields's functions.
storesobjectGenerated fields's stores.

Generated stores's props

PropTypeDescription
stores.fieldName_valueReadable<T['fieldName']>Readable store holding field's value
stores.fieldName_touchedReadable<boolean>The field have been touched or not
stores.fieldName_dirtyReadable<boolean>The field value been changed or not
stores.fieldName_errorReadable<string>The field validation error message, if any
stores.fieldName_validReadable<boolean>The field value is valid or not

Generated field's functions

PropTypeDescription
fields.fieldName.updateValue(updater: Updater<T['fieldName']>) => voidFunction to update field's value
stores.fieldName.setValue(val: T['fieldName']) => voidFunction to set field's value
stores.fieldName.handleChange(val: unknown) => voidCallback to update field's value
stores.fieldName.handleBlur() => voidCallback to mark field as touched
stores.fieldName.reset() => voidReset field to original state
stores.fieldName.setError(msg: string) => voidManually set field error
stores.fieldName.setTouched(val: boolean) => voidManually set touched state

Features

  • Use Svelte native stores
  • Fast: only update what changed, and you only subscribe to what you need
  • Validation using Zod (Peer dependencies)
  • TypeScript
  • Minimal bundle

Extra

Why the cactus 🌵?

> For its resilience

TODO

  • More tests
  • Support nested object
  • Support array

Contributions

Any contributions are highly appreciate, please make a pull-request. If you would like to discuses a new feature, please create an issue first.

1.6.1

9 months ago

1.6.0

9 months ago

1.5.0

9 months ago

1.4.2

9 months ago

1.4.1

9 months ago

1.4.0

9 months ago

1.2.4

10 months ago

1.2.3

10 months ago

1.3.0

10 months ago

1.2.0

2 years ago

1.1.0

2 years ago

1.2.2

2 years ago

1.0.4

2 years ago

1.2.1

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.1.0

2 years ago

0.0.15

2 years ago

0.0.14

2 years ago

0.0.13

2 years ago

0.0.12

2 years ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago