使用者是一群愛惡作劇的人,如果給他們機會,他們會提交各種毫無意義的資料。為了防止他們製造混亂,驗證表單資料非常重要。
第一道防線是瀏覽器的內建表單驗證,它讓你可以輕鬆地將<input>
標記為必填
src/routes/+page
<form method="POST" action="?/create">
<label>
add a todo
<input
name="description"
autocomplete="off"
required
/>
</label>
</form>
試著在<input>
為空時按下 Enter。
這種驗證方式很有幫助,但還不夠。有些驗證規則(例如唯一性)無法使用<input>
屬性來表達,而且無論如何,如果使用者是高手駭客,他們可能會使用瀏覽器的開發人員工具刪除這些屬性。為了防範這些惡作劇,您應該始終使用伺服器端驗證。
在src/lib/server/database.js
中,驗證描述是否存在且唯一
src/lib/server/database
export function createTodo(userid, description) {
if (description === '') {
throw new Error('todo must have a description');
}
const todos = db.get(userid);
if (todos.find((todo) => todo.description === description)) {
throw new Error('todos must be unique');
}
todos.push({
id: crypto.randomUUID(),
description,
done: false
});
}
嘗試提交重複的待辦事項。糟了!SvelteKit 將我們帶到一個看起來不友善的錯誤頁面。在伺服器上,我們看到「待辦事項必須是唯一的」錯誤,但 SvelteKit 會向使用者隱藏意外的錯誤訊息,因為它們通常包含敏感資料。
最好停留在同一個頁面,並提供錯誤發生的指示,以便使用者可以修正它。為了做到這一點,我們可以使用fail
函式從動作傳回資料以及適當的 HTTP 狀態碼
src/routes/+page.server
import { fail } from '@sveltejs/kit';
import * as db from '$lib/server/database.js';
export function load({ cookies }) {...}
export const actions = {
create: async ({ cookies, request }) => {
const data = await request.formData();
try {
db.createTodo(cookies.get('userid'), data.get('description'));
} catch (error) {
return fail(422, {
description: data.get('description'),
error: error.message
});
}
}
在src/routes/+page.svelte
中,我們可以透過form
prop 存取傳回的值,該 prop 僅在表單提交後才會被填入
src/routes/+page
<script>
let { data, form } = $props();
</script>
<div class="centered">
<h1>todos</h1>
{#if form?.error}
<p class="error">{form.error}</p>
{/if}
<form method="POST" action="?/create">
<label>
add a todo:
<input
name="description"
value={form?.description ?? ''}
autocomplete="off"
required
/>
</label>
</form>
您也可以從動作傳回資料,而不將其包裝在
fail
中 — 例如,在資料儲存時顯示「成功!」訊息 — 並且可以透過form
prop 使用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<script>
let { data } = $props();
</script>
<div class="centered">
<h1>todos</h1>
<form method="POST" action="?/create">
<label>
add a todo:
<input
name="description"
autocomplete="off"
/>
</label>
</form>
<ul class="todos">
{#each data.todos as todo (todo.id)}
<li>
<form method="POST" action="?/delete">
<input type="hidden" name="id" value={todo.id} />
<span>{todo.description}</span>
<button aria-label="Mark as complete"></button>
</form>
</li>
{/each}
</ul>
</div>
<style>
.centered {
max-width: 20em;
margin: 0 auto;
}
label {
width: 100%;
}
input {
flex: 1;
}
span {
flex: 1;
}
button {
border: none;
background: url(./remove.svg) no-repeat 50% 50%;
background-size: 1rem 1rem;
cursor: pointer;
height: 100%;
aspect-ratio: 1;
opacity: 0.5;
transition: opacity 0.2s;
}
button:hover {
opacity: 1;
}
.saving {
opacity: 0.5;
}
</style>