Welcome to the fifth lesson in our Advanced State Management and Persistence course! So far, we've built a functional Kanban board application with task management capabilities, localStorage persistence, and a notification system that provides immediate feedback when users add tasks.
Now, we're going to enhance our application further by implementing robust form validation and error handling. While our notification system tells users when something has happened successfully, form validation prevents errors before they occur by ensuring that users provide valid input.
Why Form Validation Matters
Form validation is a critical aspect of any application that accepts user input. Without validation, users might submit incomplete or invalid data, leading to errors, unexpected behavior, or even security vulnerabilities. By validating input on the client side, we can:
Provide immediate feedback to users about input errors
Prevent invalid data from being processed or stored
Improve the overall user experience by guiding users toward correct input
In our Kanban board, we'll focus on validating the task creation form. We'll ensure that task titles are provided and within reasonable length limits, and that descriptions don't exceed the maximum length. We'll also add visual indicators and error messages to guide users.
Building on Our Notification System
Additionally, we'll create a global error page to handle unexpected application errors, providing users with information about what went wrong and how to recover.
This lesson builds directly on our notification system from the previous lesson. While notifications tell users what happened after an action, validation guides users before and during form submission. Together, these features create a comprehensive feedback system that improves the user experience at every step.
Let's get started by enhancing our TaskForm component with validation state!
Setting Up Validation State Variables
The first step in implementing form validation is to set up the state we'll need to track validation errors and form submission status. We'll enhance our existing TaskForm component with additional state variables using Svelte's runes.
Let's update our TaskForm component to include validation state:
Svelte
<script> import { addTask } from '$lib/taskStore.svelte.js'; let title = $state(''); let description = $state(''); let errors = $state({}); let isSubmitting = $state(false); // Reactive values using $derived const characterCount = $derived(description.length); const isWarning = $derived(characterCount > 180); // Validation and submission functions will go here</script>
We've added two new state variables:
errors: An object that will store validation errors for each field. We initialize it as an empty object using $state({}).
isSubmitting: A boolean flag that tracks whether a form submission is in progress. We initialize it as false using $state(false).
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Adding Reactive Derived Values
We've also added a new derived value:
isWarning: A boolean that becomes true when the character count exceeds 180 characters. This will help us provide a visual warning before the user reaches the maximum limit.
These state variables will work together to manage the validation and submission process:
The errors object will store any validation errors by field name (e.g., errors.title for title field errors).
The isSubmitting flag will prevent multiple submissions and provide visual feedback during submission.
The isWarning derived value will help us show a warning when the user approaches the character limit.
By using Svelte's runes for these state variables, we ensure that any changes to them will automatically trigger UI updates. For example, when we set an error message for the title field, the UI will immediately show that error without any additional code.
This reactive approach to form validation makes our code cleaner and more maintainable. Instead of manually updating the UI when validation state changes, we can focus on the validation logic itself and let Svelte handle the UI updates.
Creating the Validation Function
With our validation state in place, we need to create a function that checks the form inputs and returns any validation errors. This function will be called before form submission to ensure that only valid data is processed.
Let's add a validateForm function to our TaskForm component:
<script> import { addTask } from '$lib/taskStore.svelte.js'; let title = $state(''); let description = $state(''); let errors = $state({}); let isSubmitting = $state(false); // Reactive values using $derived const characterCount = $derived(description.length); const isWarning = $derived(characterCount > 180); function validateForm() { let formErrors = {}; // Validate title if (!title.trim()) { formErrors.title = 'Title is required'; } else if (title.length > 50) { formErrors.title = 'Title must be less than 50 characters'; } // Validate description if (description.length > 200) { formErrors.description = 'Description must be less than 200 characters'; } return formErrors; }</script>
Our validateForm function performs several important checks:
It creates a local formErrors object to store any validation errors.
It validates the title field by checking:
If the title is empty (after trimming whitespace)
If the title exceeds the maximum length of 50 characters
It validates the description field by checking:
If the description exceeds the maximum length of 200 characters
Finally, it returns the formErrors object, which will be empty if there are no validation errors.
Understanding Validation Best Practices
This validation function follows a common pattern in form validation:
Check each field against its validation rules
Collect all errors in a single object
Return the complete set of errors
By returning all errors at once rather than stopping at the first error, we allow users to fix all issues in a single pass rather than encountering them one by one.
The validation rules we've implemented are straightforward but effective:
Requiring a title ensures that each task has a clear identifier
Limiting the title length keeps the UI clean and prevents abuse
Limiting the description length ensures reasonable storage requirements and maintains UI consistency
These validation rules align with our application's needs while providing clear guidance to users. Now, let's use this validation function in our form submission process.
Implementing the Submit Handler
Now that we have our validation function, we need to integrate it into the form submission process. We'll update our handleSubmit function to validate the form before submission and handle any errors that occur during the submission process.
Let's implement the updated handleSubmit function:
<script> import { addTask } from '$lib/taskStore.svelte.js'; let title = $state(''); let description = $state(''); let errors = $state({}); let isSubmitting = $state(false); // Reactive values using $derived const characterCount = $derived(description.length); const isWarning = $derived(characterCount > 180); function validateForm() { let formErrors = {}; // Validate title if (!title.trim()) { formErrors.title = 'Title is required'; } else if (title.length > 50) { formErrors.title = 'Title must be less than 50 characters'; } // Validate description if (description.length > 200) { formErrors.description = 'Description must be less than 200 characters'; } return formErrors; } async function handleSubmit(e) { e.preventDefault(); isSubmitting = true; errors = validateForm(); if (Object.keys(errors).length === 0) { try { await addTask(title, description); title = ''; description = ''; } catch (error) { errors.form = 'Failed to add task: ' + error.message; } } isSubmitting = false; }</script>
Our updated handleSubmit function now includes several important steps:
It prevents the default form submission behavior with e.preventDefault().
It sets isSubmitting to true to indicate that submission is in progress.
It calls our validateForm function and stores the result in the errors state.
Error Handling and Success Management
The submission function continues with these steps:
It checks if there are any validation errors by counting the keys in the errors object.
If there are no validation errors, it:
Uses a try/catch block to handle potential errors during task creation
Calls the addTask function with the title and description
Clears the form fields on success
Sets a form-level error message if an error occurs
Finally, it sets isSubmitting back to false to indicate that submission is complete.
The async/await pattern is used here to handle the asynchronous addTask function. While our current implementation of addTask is synchronous, using async/await makes our code future-proof for when we might want to add asynchronous behavior, such as saving tasks to a remote server.
The try/catch block is crucial for error handling. If an error occurs during task creation, we catch it and set a form-level error message that will be displayed to the user. This ensures that users are informed of any issues that occur during submission.
By setting isSubmitting to true during submission and back to false afterward, we can disable the submit button during submission to prevent multiple submissions and provide visual feedback to users.
Creating the Form Template
With our validation logic in place, we need to update the form template to display validation errors and provide visual feedback to users. Let's enhance our TaskForm template:
This CSS provides styling for all our validation elements:
The .required class makes the asterisk red to indicate required fields
The .error class adds a red border to fields with validation errors
The .error-message and .error-text classes style error messages with red text and backgrounds
The .char-count class positions the character count in the bottom right of the textarea
The .warning modifier changes the character count color to orange when approaching the limit
The :disabled state for the button changes its appearance and cursor when submission is in progress
With these styles in place, our form now provides clear visual feedback about validation status and submission progress.
Testing the Validation System
Let's see how this works in practice:
If a user tries to submit the form without a title, they'll see a red error message: "Title is required."
If a user enters a title longer than 50 characters, they'll see: "Title must be less than 50 characters."
As a user types in the description field, they'll see a character count that turns orange when they exceed 180 characters.
If a user exceeds 200 characters in the description, they'll see: "Description must be less than 200 characters."
During submission, the submit button will be disabled and change to show "Adding..." to prevent multiple submissions.
If any error occurs during the submission process, the user will see a form-level error message explaining what went wrong.
Creating a Global Error Page
As mentioned in our introduction, we also want to handle unexpected application errors gracefully. Svelte provides a built-in mechanism for this through the +error.svelte file. Let's create a global error page that will catch any unhandled errors in our application.
Error Information: Displays the error message from page.error.message
User-Friendly Interface: Shows a gentle message with an emoji to make the error less intimidating
Recovery Option: Provides a "Reload" button that refreshes the page, allowing users to try again
Consistent Styling: Uses the same color scheme as our form validation errors
The +error.svelte file in Svelte is automatically used whenever an unhandled error occurs in your application. This ensures that users always see a friendly error page instead of a blank screen or confusing error message.
<script> import { addTask } from '$lib/taskStore.svelte.js'; let title = $state(''); let description = $state(''); let errors = $state({}); let isSubmitting = $state(false); // Reactive values using $derived const characterCount = $derived(description.length); const isWarning = $derived(characterCount > 180); function validateForm() { let formErrors = {}; // Validate title if (!title.trim()) { formErrors.title = 'Title is required'; } else if (title.length > 50) { formErrors.title = 'Title must be less than 50 characters'; } // Validate description if (description.length > 200) { formErrors.description = 'Description must be less than 200 characters'; } return formErrors; }</script>
Svelte
<script> import { addTask } from '$lib/taskStore.svelte.js'; let title = $state(''); let description = $state(''); let errors = $state({}); let isSubmitting = $state(false); // Reactive values using $derived const characterCount = $derived(description.length); const isWarning = $derived(characterCount > 180); function validateForm() { let formErrors = {}; // Validate title if (!title.trim()) { formErrors.title = 'Title is required'; } else if (title.length > 50) { formErrors.title = 'Title must be less than 50 characters'; } // Validate description if (description.length > 200) { formErrors.description = 'Description must be less than 200 characters'; } return formErrors; } async function handleSubmit(e) { e.preventDefault(); isSubmitting = true; errors = validateForm(); if (Object.keys(errors).length === 0) { try { await addTask(title, description); title = ''; description = ''; } catch (error) { errors.form = 'Failed to add task: ' + error.message; } } isSubmitting = false; }</script>
In this lesson, we've successfully implemented a comprehensive form validation system for our Kanban board application. Here's what we accomplished:
Key Features Implemented:
Validation State Management: Added reactive state variables to track errors and submission status
Validation Logic: Created a validateForm function that checks title and description fields
Async Form Submission: Implemented proper error handling with try/catch blocks
User-Friendly Feedback: Added visual indicators, error messages, and character counts
Submission States: Disabled forms and buttons during submission to prevent multiple submissions
Benefits to Users:
Immediate feedback about input errors before submission
Clear visual indicators for required fields and validation states
Character count warnings to guide proper input length
Comprehensive error messages that help users understand what went wrong
Smooth user experience with proper loading states
Technical Highlights:
Used Svelte's $state and $derived runes for reactive validation state
Implemented async/await pattern for future-proof asynchronous operations
Created a modular validation function that's easy to extend
Added comprehensive CSS styling for all validation states
This validation system complements our notification system from the previous lesson, creating a complete feedback system that guides users before, during, and after form submissions. The combination ensures users always know the status of their actions and can quickly correct any issues.
In the next lesson, we'll build on this foundation by adding more advanced validation features like custom validation rules and real-time validation as users type.