Form Validation
Свайпніть щоб показати меню
Frontend applications often need to validate user input before submitting data. Validation helps prevent incomplete or incorrect information from being sent to the application or server.
Svelte makes validation easier through reactive variables and conditional rendering.
Why Validation Matters
Validation improves both usability and data quality.
Applications commonly validate:
- Empty fields;
- Password length;
- Email format;
- Required selections;
- Input limits.
Without validation, users could submit incomplete or invalid data.
Creating a Simple Validation Rule
Open App.svelte and add the following code:
<script>
let password = "";
</script>
<input
type="password"
bind:value={password}
placeholder="Enter password"
/>
Now add conditional validation:
{#if password.length < 6}
<p>Password must contain at least 6 characters.</p>
{/if}
The validation message appears automatically when the password is too short.
Reactive Validation
Svelte updates validation messages automatically because the interface reacts to changes in the input value.
As the user types, the condition re-evaluates and the UI updates immediately.
This creates a smooth and interactive form experience.
Validating Multiple Fields
Applications often validate several inputs at once.
<script>
let email = "";
let password = "";
</script>
{#if !email.includes("@")}
<p>Please enter a valid email.</p>
{/if}
{#if password.length < 6}
<p>Password is too short.</p>
{/if}
Each validation rule responds independently to user input.
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат