⚠️ 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
Published 4 years ago
Updated 2 years ago

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.

egghead
egghead
~ 7 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today