show registration errors on register form

This commit is contained in:
Ilion Beyst 2022-04-09 10:18:49 +02:00
parent cc7014b04b
commit f59bf07d57

View file

@ -2,7 +2,9 @@
let username: string | undefined; let username: string | undefined;
let password: string | undefined; let password: string | undefined;
const onSubmit = () => { let registrationErrors: string[] = [];
const onSubmit = async () => {
if (username === undefined || username.trim() === "") { if (username === undefined || username.trim() === "") {
return; return;
} }
@ -11,7 +13,9 @@
return; return;
} }
fetch("/api/register", { registrationErrors = [];
const response = await fetch("/api/register", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -20,17 +24,29 @@
username, username,
password, password,
}), }),
}) });
.then((resp) => resp.json())
.then((data) => { if (!response.ok) {
console.log(data); const resp = await response.json();
}); const error = resp["error"];
if (response.status == 422 && error["type"] === "validation_failed") {
registrationErrors = error["validation_errors"];
}
}
}; };
</script> </script>
<div class="page-card"> <div class="page-card">
<div class="page-card-content"> <div class="page-card-content">
<h1 class="page-card-header">Create account</h1> <h1 class="page-card-header">Create account</h1>
{#if registrationErrors.length > 0}
<ul class="error-message-list">
{#each registrationErrors as errorMessage}
<li class="error-message">{errorMessage}</li>
{/each}
</ul>
{/if}
<form class="account-form" on:submit|preventDefault={onSubmit}> <form class="account-form" on:submit|preventDefault={onSubmit}>
<label for="username">Username</label> <label for="username">Username</label>
<input name="username" bind:value={username} /> <input name="username" bind:value={username} />
@ -43,4 +59,8 @@
<style lang="scss"> <style lang="scss">
@import "src/styles/account_forms.scss"; @import "src/styles/account_forms.scss";
</style>
.error-message-list {
color: red;
}
</style>