An open API service indexing awesome lists of open source software.

https://github.com/probablykasper/niceform

Convenient form validation and typing for SvelteKit
https://github.com/probablykasper/niceform

Last synced: 12 months ago
JSON representation

Convenient form validation and typing for SvelteKit

Awesome Lists containing this project

README

          

# niceform
Convenient form validation and typing for SvelteKit. Based on Superforms and Zod.

Might turn this into an actual package later

Features
- `name` attribute typing
- Multiple forms
- i18n
- Snapshots

### Example `+page.server.ts`
```ts
import { z } from 'zod'
import { nice_form } from '$lib/niceform'

const schema = z.object({
name: z.string(),
})

export const actions = {
async default(event) {
const form = await nice_form.zod(schema, event)
if (!form.valid) {
return form.fail(400)
}
if (form.data.name === 'Hi') {
return form.set_error('name', 'You are a failure')
}

return {
success: true,
}
},
}
```

### Example Input wrapper component

Includes type-safe `name` attribute, automatic error messages and label with automatic ID

image

```svelte

import { sequential_num, type AddFormProps, type PartialNiceForm } from './niceform'
import type { HTMLInputAttributes } from 'svelte/elements'

let {
form,
label,
value = $bindable(),
...props
}: AddFormProps<HTMLInputAttributes, F> = $props()

let errors = $derived(form?.errors ?? {})

const id = 'input-' + sequential_num()


{#if label}
{label}
{/if}

{#if props.name && errors[props.name]}
{errors[props.name]}
{/if}

```

### i18n example
```ts
import { z } from 'zod'
import * as m from '$lib/paraglide/messages'
import { set_error_map } from './niceform'

export const form_errors = set_error_map({
invalid_email: m.invalid_email,
})

export const email_schema = z.string().email(form_errors.invalid_email).max(100)
```

### Snapshots

Might change this API

```ts

import { enhance } from '$app/forms'
import { auto_snapshot } from '$lib/niceform'

const snapshotter = auto_snapshot()
export const snapshot = auto_snapshot()

```