当然!让我们逐步介绍验证和提交Svelte表单的示例。在此示例中,我们将使用Svelte的内置验证功能,而无需任何外部库。
- 在Svelte组件中设置形式结构。这是一个带有两个字段的
LoginForm.svelte
组件的示例:用户名和密码。
<script>
let username = '';
let password = '';
</script>
<form on:submit={handleSubmit}>
<label>
Username:
<input type="text" bind:value={username} />
</label>
<label>
Password:
<input type="password" bind:value={password} />
</label>
<button type="submit">Submit</button>
</form>
- 添加必要的表单验证逻辑。在此示例中,我们将在允许提交之前检查两个字段。
<script>
let username = '';
let password = '';
let errors = {};
function handleSubmit(event) {
event.preventDefault();
// Clear previous errors
errors = {};
if (username === '') {
errors.username = 'Please enter a username.';
}
if (password === '') {
errors.password = 'Please enter a password.';
}
if (Object.keys(errors).length === 0) {
// Form is valid, perform form submission logic
submitForm();
}
}
function submitForm() {
// You can make an API call or perform any necessary data processing here
console.log('Form submitted!');
}
</script>
-
将事件处理程序附加到表单和表单字段。在这种情况下,我们将捕获表格的
on:submit
事件并使用bind:value
绑定输入字段的值。 -
显示验证错误。如果有任何验证错误,我们将更新标记以显示错误消息。
<form on:submit={handleSubmit}>
<label>
Username:
<input type="text" bind:value={username} />
{#if errors.username}<p class="error">{errors.username}</p>{/if}
</label>
<label>
Password:
<input type="password" bind:value={password} />
{#if errors.password}<p class="error">{errors.password}</p>{/if}
</label>
<button type="submit">Submit</button>
</form>
<style>
.error {
color: red;
font-size: 0.8rem;
}
</style>
- 向用户提供反馈。表单提交逻辑执行后,我们可以添加成功消息。
<script>
let username = '';
let password = '';
let errors = {};
let submissionSuccess = false;
function handleSubmit(event) {
event.preventDefault();
// Clear previous errors
errors = {};
if (username === '') {
errors.username = 'Please enter a username.';
}
if (password === '') {
errors.password = 'Please enter a password.';
}
if (Object.keys(errors).length === 0) {
// Form is valid, perform form submission logic
submitForm();
}
}
function submitForm() {
// You can make an API call or perform any necessary data processing here
// For simplicity, we'll simulate a successful submission after a 1-second delay
setTimeout(() => {
console.log('Form submitted!');
submissionSuccess = true;
}, 1000);
}
</script>
{#if submissionSuccess}
<p>Form submitted successfully!</p>
{/if}
关于作者。 Geoffrey Callaghan是Fabform.io的程序员,在form backend团队中工作。