Updated the Forms example

This commit is contained in:
Samuel Andert 2023-07-28 12:30:27 +02:00
parent 9c08a2cf11
commit 4d310220dd
6 changed files with 143 additions and 57 deletions

View File

@ -0,0 +1,119 @@
<script lang="ts">
import { superForm, message } from 'sveltekit-superforms/client';
import { UserSchema } from '$lib/types/UserSchema';
import { afterUpdate } from 'svelte';
import { writable } from 'svelte/store';
const initialFormData = { name: '', email: '' };
const { form, errors, validate, constraints, capture, restore } = superForm(initialFormData, {
validators: UserSchema,
warnings: {
noValidationAndConstraints: false
},
validationMethod: 'oninput', // Trigger validation on input events
// Set the clearOnSubmit option to clear both errors and message on submit
clearOnSubmit: 'errors-and-message'
});
export const snapshot = { capture, restore };
const successMessage = writable<string | null>(null);
async function handleSubmit() {
// Manually validate the form
const validationResult = await validate();
// Prevent submission if there are errors
if (!validationResult.valid) {
return;
}
// Here, we'll just log the form data
console.log(form);
// Set the success message after successful submission
successMessage.set('Form submitted successfully!');
}
function handleReset() {
// Reset the form and remove the message
form.set({});
successMessage.set(null);
}
// After update, scroll to the message container for better user experience
afterUpdate(() => {
const messageContainer = document.getElementById('message-container');
if (messageContainer) {
messageContainer.scrollIntoView({ behavior: 'smooth' });
}
});
</script>
<div class="flex items-center justify-center min-h-screen">
{#if $successMessage}
<!-- Display the success message instead of the form -->
<aside class="w-full max-w-md p-4 alert variant-ghost" id="message-container">
<!-- Icon -->
<!-- <div>(icon)</div> -->
<!-- Message -->
<div class="alert-message">
<h3 class="h3">Success</h3>
<p>{$successMessage}</p>
</div>
<!-- Actions (in this case, only the Reset button) -->
<div class="alert-actions">
<button
class="px-4 py-2 mt-4 text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
on:click={handleReset}
>
Reset
</button>
</div>
</aside>
{:else}
<form on:submit|preventDefault={handleSubmit} class="w-full max-w-md">
<div class="mb-4">
{#if $errors.name}
<span class="block mb-2 font-semibold text-red-500">{$errors.name}</span>
{:else}
<label for="name" class="block mb-2 font-semibold text-white">Name</label>
{/if}
<input
name="name"
type="text"
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form.name}
aria-invalid={$errors.name ? 'true' : undefined}
{...constraints.name}
/>
</div>
<div class="mb-4">
{#if $errors.email}
<span class="block mb-2 font-semibold text-red-500">{$errors.email}</span>
{:else}
<label for="email" class="block mb-2 font-semibold text-white">Email</label>
{/if}
<input
name="email"
type="email"
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form.email}
aria-invalid={$errors.email ? 'true' : undefined}
{...constraints.email}
/>
</div>
<button
type="submit"
class="w-full px-4 py-2 mt-4 text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={$errors.name || $errors.email}
>
Submit
</button>
</form>
{/if}
</div>

View File

@ -1,5 +1,17 @@
import { z } from 'zod';
// Define custom validation messages
const validationMessages = {
name: {
minLength: 'Name must be at least 3 characters.',
maxLength: 'Name must contain at most 10 characters.',
},
email: {
isEmail: 'Invalid email address.',
},
};
export const UserSchema = z.object({
name: z.string().min(3).max(10)
name: z.string().min(3, validationMessages.name.minLength).max(10, validationMessages.name.maxLength),
email: z.string().email(validationMessages.email.isEmail),
});

View File

@ -11,11 +11,12 @@
},
layout: {
areas: `
"main aside"
"main aside"
"footer footer";
`,
columns: '1fr 1fr',
rows: '1fr auto'
rows: '1fr 1fr auto'
},
children: [
{
@ -36,8 +37,8 @@
services: ['helloEarthAlert']
},
{
id: 'testflows',
component: 'Flows',
id: 'form',
component: 'Form',
slot: 'aside'
},
{

View File

@ -1,56 +1,10 @@
<script lang="ts">
import { superForm } from 'sveltekit-superforms/client';
import { UserSchema } from '$lib/types/UserSchema';
<script>
import Composite from '$lib/core/Composite.svelte';
const initialFormData = { name: '' };
const { form, errors, validate, constraints } = superForm(initialFormData, {
validators: UserSchema,
warnings: {
noValidationAndConstraints: false
},
validationMethod: 'oninput' // Trigger validation on input events
});
async function handleSubmit() {
// Manually validate the form
const validationResult = await validate();
// Prevent submission if there are errors
if (!validationResult.valid) {
return;
}
// Here, we'll just log the form data
console.log(form);
}
let composite = {
id: 'validationexample',
component: 'Form'
};
</script>
<div class="flex items-center justify-center min-h-screen">
<form on:submit|preventDefault={handleSubmit} class="w-full max-w-md">
<div class="mb-4">
{#if $errors.name}
<span class="block mb-2 font-semibold text-red-500">{$errors.name}</span>
{:else}
<label for="name" class="block mb-2 font-semibold text-white">Name</label>
{/if}
<input
name="name"
type="text"
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form.name}
aria-invalid={$errors.name ? 'true' : undefined}
{...constraints.name}
/>
</div>
<button
type="submit"
class="w-full px-4 py-2 text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={$errors.name}
>
Submit
</button>
</form>
</div>
<Composite {composite} />