⚠️ This lesson is retired and might contain outdated information.

Refactor a Svelte Form to Use svelte-forms-lib Components

Andrew Smith
InstructorAndrew Smith
Share this video with your friends

Social Share Links

Send Tweet

You will learn how to create simple forms quicker with the helper components provided by svelte-forms-lib. We will start off with a form that contains some validation rules along with input fields and error messages.

Instructor: [0:00] Let's import the field and form components from the Svelte forms library. Let's replace the form tags with the form component. If we submit the form, nothing will happen. Let's change the createForm() function to only return object and assign it to a variable called formProps. We can now pass the formProps to our form component using the spread operator.

[0:22] Let's replace the username input field with the field component we imported earlier. Add a name property to the field component. Then remove the on:change and bind value directives from the component.

[0:35] Let's repeat the same process for our password input field by replacing the input with the field component, adding a name, and removing the on:change and bind value directives. Let's remove the arrow if tags and we should now see our form displaying again.

[0:51] If we click the Sign in button on the form, we can see we no longer have error messages. We can fix this by importing the ErrorMessage component from svelte-forms-lib. Inside of our html, below the username field component, we will place the ErrorMessage component and add a name property with the value of username.

[1:14] If we click Sign in, we should see an error message. Let's repeat the same for the password by copying the one for the username and replacing the name property to password. Let's hit Sign in again and you will notice the form looks a little broken. Let's add some classes to fix this. Now hit Sign in again and it's all looking good now.