https://github.com/pixelmund/svom
SvelteKit form validations for the server and client, using zod and zod-form-data
https://github.com/pixelmund/svom
Last synced: about 1 month ago
JSON representation
SvelteKit form validations for the server and client, using zod and zod-form-data
- Host: GitHub
- URL: https://github.com/pixelmund/svom
- Owner: pixelmund
- License: mit
- Created: 2023-01-13T21:50:06.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-01-13T21:50:23.000Z (over 2 years ago)
- Last Synced: 2024-04-25T22:41:04.326Z (about 1 year ago)
- Language: TypeScript
- Size: 27.3 KB
- Stars: 8
- Watchers: 2
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# svom
SvelteKit form validations for the server and client, using zod and zod-form-data
## Getting Started
Install the package:
```bash
npm install svom
```
## Usage
### Server
```ts
// src/routes/register/+page.server.ts
import { z } from 'zod';
import { validate, zfd } from 'svom';
import type { Actions } from './$types';
import db from '$db';const SignUpSchema = zfd.formData({
name: zfd.text(z.string().min(1)),
age: zfd.numeric(z.number().min(18)),
email: zfd.text(z.string().email()),
password: zfd.text(z.string().min(8))
});export const actions = {
signUp: validate(SignUpSchema, async ({ data, fail }) => {
const { name, age, email, password } = data;if (db.user.exists(email)) {
return fail({ email: 'Email already exists' });
}// ... do something with the data
})
} satisfies Actions;
```### Client
```svelte
import { createForm } from 'svom';
import SubmitButton from '$lib/SubmitButton.svelte';
import Input from '$lib/Input.svelte';
// We're using a shared file for the schema, but you can also define it in this file for custom client validation
import { SignUpSchema } from './validation';const { enhance } = createForm({
schema: SignUpSchema,
onSubmit: async (data, { form, action, result }) => {
console.log({ data, other });
}
});
```
```svelte
import { useField } from 'svom';
export let name: string;
export let type: string = 'text';
export let disabled: boolean = false;
export let initialValue: any = '';const { error, isSubmitting, value } = useField(name, initialValue);
{#if $error}
{$error}
{/if}
``````svelte
import { useForm } from '$lib';
const { isSubmitting } = useForm();Submit
button:disabled {
opacity: 0.5;
}```